-
Notifications
You must be signed in to change notification settings - Fork 26
Initializing thick client #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
I'll help you generate the summary for this extensive pull request. I'll break it down into sections as requested. WalkthroughThis pull request introduces a comprehensive set of changes across multiple vendor packages, primarily focusing on enhancing system-level interactions, error handling, and utility functions. The changes span packages like Changes
Sequence DiagramsequenceDiagram
participant Client
participant DiceDB
participant Cache
Client->>DiceDB: PING
DiceDB-->>Client: PONG
Client->>DiceDB: SET foo bar
DiceDB-->>Client: OK
Client->>DiceDB: GET foo
DiceDB->>Cache: Check cache
Cache-->>DiceDB: Not found
DiceDB-->>Client: bar
Client->>DiceDB: GET foo1
DiceDB-->>Client: (nil)
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 20
🔭 Outside diff range comments (1)
vendor/github.com/dgraph-io/ristretto/.go-version (1)
1-2
: 💡 Verification agent🧩 Analysis chain
Verify that Go 1.19 aligns with go.mod and other build configurations.
Ensure all CI/CD stages, Dockerfiles, and
go.mod
files consistently use Go 1.19 to avoid version mismatches or build failures.
🏁 Script executed:
#!/bin/bash # Searching for references to Go version in the project rg 'go 1\.'Length of output: 230
Attention: Inconsistent Go Version Configurations Detected
Our verification shows that the vendored file
vendor/github.com/dgraph-io/ristretto/.go-version
specifies Go 1.19, while the rootgo.mod
is using Go 1.24.0. Additionally,vendor/modules.txt
includes several explicit Go versions (1.11, 1.16, 1.17, 1.19, 1.21), which further highlights potential version mismatches.•
vendor/github.com/dgraph-io/ristretto/.go-version
: Lists Go 1.19.
•go.mod
: Sets the project to Go 1.24.0.
•vendor/modules.txt
: Contains multiple Go version references.Please update the configuration so that all CI/CD stages, Dockerfiles, and build files consistently use the intended Go version. This may involve updating the vendored file (if it’s safe to do so) or confirming that the distinction is intentional and documented.
🧹 Nitpick comments (156)
vendor/golang.org/x/sys/unix/.gitignore (1)
1-2
: Appropriate .gitignore entries for build artifacts.Adding
_obj/
andunix.test
is an effective way to ensure that build artifacts or temporary test outputs are not tracked by Git. For enhanced maintainability, consider adding brief inline comments to clarify why these entries are being ignored.vendor/github.com/google/uuid/CONTRIBUTING.md (2)
3-3
: Nitpick: Fix grammatical number in contribution message.
The line "We definitely welcome patches and contribution to this project!" uses a singular noun "contribution" alongside "patches." Consider changing it to "contributions" for grammatical agreement.-We definitely welcome patches and contribution to this project! +We definitely welcome patches and contributions to this project!🧰 Tools
🪛 LanguageTool
[uncategorized] ~3-~3: The grammatical number of this noun doesn’t look right. Consider replacing it.
Context: ...bute We definitely welcome patches and contribution to this project! ### Tips Commits mus...(AI_EN_LECTOR_REPLACEMENT_NOUN_NUMBER)
23-24
: Refactor wording for legal requirements.
The phrase "In order to protect both you and ourselves, you will need to sign the" can be simplified for clarity and brevity. Consider rephrasing it to something like "To protect both you and us, please sign the Contributor License Agreement."-In order to protect both you and ourselves, you will need to sign the -[Contributor License Agreement](https://cla.developers.google.com/clas). +To protect both you and us, please sign the [Contributor License Agreement](https://cla.developers.google.com/clas).vendor/github.com/google/uuid/node_net.go (3)
11-11
: Consider thread safety for shared cache variable.The global
interfaces
variable is used as a cache but lacks mutex protection. This could lead to race conditions if multiple goroutines callgetHardwareInterface
concurrently.Consider adding a mutex to protect access to this shared resource:
package uuid import ( + "sync" "net" ) var interfaces []net.Interface // cached list of interfaces +var interfacesMutex sync.RWMutexAnd in the function:
func getHardwareInterface(name string) (string, []byte) { + interfacesMutex.RLock() if interfaces == nil { + interfacesMutex.RUnlock() + interfacesMutex.Lock() + // Double check in case another goroutine initialized it + if interfaces == nil { var err error interfaces, err = net.Interfaces() if err != nil { + interfacesMutex.Unlock() return "", nil } + } + interfacesMutex.Unlock() + interfacesMutex.RLock() } // Rest of function... + defer interfacesMutex.RUnlock()
19-33
: Consider implementing cache refresh mechanism.The interfaces cache is populated only once and never refreshed, which could be problematic if network interfaces change during the application's lifetime.
Consider adding a way to periodically refresh the cache or providing an explicit method to invalidate it:
// getHardwareInterface returns the name and hardware address of interface name. // If name is "" then the name and hardware address of one of the system's // interfaces is returned. If no interfaces are found (name does not exist or // there are no interfaces) then "", nil is returned. // // Only addresses of at least 6 bytes are returned. func getHardwareInterface(name string) (string, []byte) { // Existing code... } +// refreshNetworkInterfaces forces a refresh of the cached network interfaces. +// This can be called when network configuration changes are detected. +func refreshNetworkInterfaces() { + interfacesMutex.Lock() + defer interfacesMutex.Unlock() + interfaces = nil +}
23-25
: Consider logging or exposing the error details.The function silently discards the specific error from
net.Interfaces()
, which might make debugging difficult.Consider at least logging the error or providing an option to expose it:
func getHardwareInterface(name string) (string, []byte) { if interfaces == nil { var err error interfaces, err = net.Interfaces() if err != nil { + // Optional: Add logging here + // log.Printf("Failed to get network interfaces: %v", err) return "", nil } } // Rest of function... }vendor/golang.org/x/sys/unix/dev_aix_ppc64.go (3)
13-16
: Fix documentation to refer to AIX, not LinuxThe function correctly extracts the major component of a device number for AIX systems, but the documentation incorrectly refers to a "Linux device number" instead of an "AIX device number".
-// Major returns the major component of a Linux device number. +// Major returns the major component of an AIX device number.
18-21
: Fix documentation and simplify implementationThe documentation incorrectly refers to a "Linux device number" instead of an "AIX device number". Also, the
>> 0
shift operation is unnecessary and can be removed.-// Minor returns the minor component of a Linux device number. +// Minor returns the minor component of an AIX device number. func Minor(dev uint64) uint32 { - return uint32((dev & 0x00000000ffffffff) >> 0) + return uint32(dev & 0x00000000ffffffff) }
23-29
: Fix documentation and declare constant at package levelThe documentation incorrectly refers to a "Linux device number". Also, the
DEVNO64
constant could be defined at the package level instead of within the function for better maintainability.-// Mkdev returns a Linux device number generated from the given major and minor +// Mkdev returns an AIX device number generated from the given major and minor // components. + +const DEVNO64 uint64 = 0x8000000000000000 + func Mkdev(major, minor uint32) uint64 { - var DEVNO64 uint64 - DEVNO64 = 0x8000000000000000 return ((uint64(major) << 32) | (uint64(minor) & 0x00000000FFFFFFFF) | DEVNO64) }vendor/golang.org/x/sys/unix/dev_aix_ppc.go (3)
13-16
: Fix documentation to refer to AIX, not LinuxThe function correctly extracts the major component of a device number for AIX systems, but the documentation incorrectly refers to a "Linux device number" instead of an "AIX device number".
-// Major returns the major component of a Linux device number. +// Major returns the major component of an AIX device number.
18-21
: Fix documentation to refer to AIX, not LinuxThe function correctly extracts the minor component of a device number for AIX systems, but the documentation incorrectly refers to a "Linux device number" instead of an "AIX device number".
-// Minor returns the minor component of a Linux device number. +// Minor returns the minor component of an AIX device number.
23-27
: Fix documentation to refer to AIX, not LinuxThe function correctly combines major and minor components to create a device number for AIX systems, but the documentation incorrectly refers to a "Linux device number" instead of an "AIX device number".
-// Mkdev returns a Linux device number generated from the given major and minor +// Mkdev returns an AIX device number generated from the given major and minorAlso, the parentheses around major and minor in the return statement are unnecessary and can be removed for cleaner code:
- return uint64(((major) << 16) | (minor)) + return uint64((major << 16) | minor)vendor/github.com/pkg/errors/README.md (4)
1-1
: Badge Display – Review Badge FormattingThe opening line contains multiple badge links with extensive use of exclamation marks. While this is a common and accepted practice in README files, the static analysis hints that the punctuation may be a bit excessive. Consider reviewing whether the current formatting meets your style guidelines or if a slight simplification could improve readability.
🧰 Tools
3-3
: Grammar Note on Package DescriptionThe sentence “Package errors provides simple error handling primitives.” might be read ambiguously. To enhance clarity, consider rephrasing it as “The errors package provides simple error handling primitives.” This construction clearly indicates that the package, as a singular entity, provides the functionality.
🧰 Tools
🪛 LanguageTool
[grammar] ~3-~3: It seems that the correct verb form here is “provide”.
Context: ...b.com/pkg/errors?badge) Package errors provides simple error handling primitives. `go ...(AGREEMENT_SENT_START_2)
17-17
: Punctuation Improvement SuggestionIn the sentence starting on line 17, adding a comma after “For example” would improve readability. For instance, changing it to “For example, …” aligns with common punctuation practices.
🧰 Tools
🪛 LanguageTool
[typographical] ~17-~17: After the expression ‘for example’ a comma is usually used.
Context: ...adds context to the original error. For example ```go _, err := ioutil.ReadAll(r) if er...(COMMA_FOR_EXAMPLE)
48-48
: Hyphenation Suggestion for ConsistencyIn the roadmap section on line 48, the phrase “pre Go 1.9 and Go 1.10 support” could be hyphenated for clarity. Consider revising it to “pre‑Go 1.9 and pre‑Go 1.10 support” to align with typical style guidelines for prefixes attached to version numbers.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~48-~48: Prefixes followed by proper nouns or dates are typically hyphenated.
Context: ...0 release is as follows: - 0.9. Remove pre Go 1.9 and Go 1.10 support, address outsta...(PRE_PRO_ANTI)
vendor/github.com/google/uuid/CONTRIBUTORS (1)
1-10
: Ensure Consistent Contributor Formatting.
The CONTRIBUTORS file lists contributor names, and the first entry provides an email address while the others do not. For consistency and clarity, consider either adding email addresses for all contributors or removing them altogether.vendor/github.com/dgraph-io/ristretto/z/README.md (4)
12-13
: Grammar issue in the documentation.There's a missing comma after "Nonetheless" in this sentence.
-Nonetheless bbloom should work with any other form of entries. +Nonetheless, bbloom should work with any other form of entries.🧰 Tools
🪛 LanguageTool
[duplication] ~12-~12: Possible typo: you repeated a word.
Context: ...zed for this log-entry mask: "2014/%02i/%02i %02i:%02i:%02i /info.html". Nonetheless bblo...(ENGLISH_WORD_REPEAT_RULE)
[uncategorized] ~12-~12: A comma may be missing after the conjunctive/linking adverb ‘Nonetheless’.
Context: ...4/%02i/%02i %02i:%02i:%02i /info.html". Nonetheless bbloom should work with any other form ...(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)
110-110
: Missing apostrophe in possessive form."William Fitzgeralds" should be "William Fitzgerald's" as it's a possessive form.
-It's about 3 times faster than William Fitzgeralds bitset bloom filter https://github.com/willf/bloom . +It's about 3 times faster than William Fitzgerald's bitset bloom filter https://github.com/willf/bloom .🧰 Tools
🪛 LanguageTool
[uncategorized] ~110-~110: Possible missing comma found.
Context: ...r than William Fitzgeralds bitset bloom filter https://github.com/willf/bloom . And it...(AI_HYDRA_LEO_MISSING_COMMA)
129-129
: Grammar issue with countable nouns.When referring to countable items like "collisions," use "fewer" instead of "less."
-smdb is about as fast as fnv64a but gives less collisions with the dataset +smdb is about as fast as fnv64a but gives fewer collisions with the dataset🧰 Tools
🪛 LanguageTool
[grammar] ~129-~129: The auxiliary verb ‘do’ requires the base form of the verb.
Context: ...om32) using modified sdbm, bloom32 does hashing with only 2 bit shifts, one xor and one...(DID_BASEFORM)
[grammar] ~129-~129: Did you mean “fewer”? The noun “collisions” is countable.
Context: ...db is about as fast as fnv64a but gives less collisions with the dataset (see mask a...(FEWER_LESS)
1-130
: Consider updating the documentation.This README appears to be from a third-party project (github.com/AndreasBriese/bbloom) and still contains references to that project, including installation instructions. Consider updating it to reflect its incorporation into the Ristretto library or add a note explaining its origin.
🧰 Tools
🪛 LanguageTool
[duplication] ~12-~12: Possible typo: you repeated a word.
Context: ...zed for this log-entry mask: "2014/%02i/%02i %02i:%02i:%02i /info.html". Nonetheless bblo...(ENGLISH_WORD_REPEAT_RULE)
[uncategorized] ~12-~12: A comma may be missing after the conjunctive/linking adverb ‘Nonetheless’.
Context: ...4/%02i/%02i %02i:%02i:%02i /info.html". Nonetheless bbloom should work with any other form ...(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)
[uncategorized] ~15-~15: A punctuation mark might be missing here.
Context: ...(to optimize for smaller strings). sdbm http://www.cse.yorku.ca/~oz/hash.html~~ ...(AI_EN_LECTOR_MISSING_PUNCTUATION)
[uncategorized] ~110-~110: Possible missing comma found.
Context: ...r than William Fitzgeralds bitset bloom filter https://github.com/willf/bloom . And it...(AI_HYDRA_LEO_MISSING_COMMA)
[grammar] ~129-~129: The auxiliary verb ‘do’ requires the base form of the verb.
Context: ...om32) using modified sdbm, bloom32 does hashing with only 2 bit shifts, one xor and one...(DID_BASEFORM)
[grammar] ~129-~129: Did you mean “fewer”? The noun “collisions” is countable.
Context: ...db is about as fast as fnv64a but gives less collisions with the dataset (see mask a...(FEWER_LESS)
vendor/github.com/dgryski/go-farm/README.md (3)
19-19
: Consider adding a comma before “but.”For clarity and smooth readability, you can insert a comma after “thoroughly”:
- The functions mix the input bits thoroughly but are not suitable for cryptography. + The functions mix the input bits thoroughly, but are not suitable for cryptography.🧰 Tools
🪛 LanguageTool
[uncategorized] ~19-~19: Possible missing comma found.
Context: ... functions mix the input bits thoroughly but are not suitable for cryptography. All...(AI_HYDRA_LEO_MISSING_COMMA)
23-23
: Add a comma after “information.”Add a comma after “information” in “For more information please consult”:
- For more information please consult https://github.com/google/farmhash + For more information, please consult https://github.com/google/farmhash🧰 Tools
🪛 LanguageTool
[typographical] ~23-~23: Consider adding a comma here.
Context: ...nkins, and others. For more information please consult https://github.com/google/farmh...(PLEASE_COMMA)
30-30
: Fix verb agreement.Use “includes” instead of “include”:
- This project include a Makefile that allows you to test and build the project ... + This project includes a Makefile that allows you to test and build the project ...🧰 Tools
🪛 LanguageTool
[uncategorized] ~30-~30: This verb does not appear to agree with the subject. Consider using a different form.
Context: ....org for getting started. This project include a Makefile that allows you to test and ...(AI_EN_LECTOR_REPLACEMENT_VERB_AGREEMENT)
vendor/golang.org/x/sys/unix/dev_linux.go (1)
29-29
: Minor nitpick: Unnecessary zero shift.Line 29 includes a shift by 0 (
>> 0
), which is unnecessary but doesn't affect functionality. It's likely included for clarity and consistency with the encoding description.- minor := uint32((dev & 0x00000000000000ff) >> 0) + minor := uint32(dev & 0x00000000000000ff)vendor/github.com/dustin/go-humanize/bytes.go (1)
103-143
: Parsing implementation is thorough, but error messages could be more descriptive.The
ParseBytes
function correctly handles various input formats, including numbers with commas, and checks for overflow againstmath.MaxUint64
. However, the error messages could be more descriptive.Consider improving the error messages to provide more context:
- return 0, fmt.Errorf("too large: %v", s) + return 0, fmt.Errorf("value too large: %v exceeds maximum uint64 value", s)- return 0, fmt.Errorf("unhandled size name: %v", extra) + return 0, fmt.Errorf("unhandled size name: %q (expected one of: kb, mb, gb, kib, mib, gib, etc.)", extra)vendor/github.com/dgraph-io/ristretto/z/mmap_windows.go (1)
1-2
: Verify build tag syntaxThe build tag syntax
// +build windows
is the older style. Consider using the newer Go 1.17+ build tag style://go:build windows
for future compatibility, while retaining the old style for backward compatibility.-// +build windows +//go:build windows +// +build windowsvendor/golang.org/x/sys/unix/mkerrors.sh (2)
450-450
: Fix array assignment in shell scriptThe current assignment
ccflags="$@"
is attempting to assign an array to a string. This may cause unexpected behavior whenccflags
is used elsewhere.-ccflags="$@" +ccflags="$*"Alternatively, if you need to preserve the array structure:
-ccflags="$@" +ccflags=("$@")Then use
"${ccflags[@]}"
where the variable is used.🧰 Tools
🪛 Shellcheck (0.10.0)
[warning] 450-450: Assigning an array to a string! Assign as array, or use * instead of @ to concatenate.
(SC2124)
783-783
: Handle errors from the compiler executionThe final command that compiles and runs the generated C program doesn't check for errors, which could lead to silent failures.
-$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out +$CC $ccflags -o _errors _errors.c && \ + $GORUN ./_errors && \ + rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out || \ + { echo "Error generating error constants"; exit 1; }vendor/github.com/google/uuid/node.go (4)
21-25
: Lock order is reversed from conventional patternThe NodeInterface function locks the mutex after setting up the defer unlock, which reverses the typical pattern. While functionally correct, this can be confusing to readers.
func NodeInterface() string { - defer nodeMu.Unlock() nodeMu.Lock() + defer nodeMu.Unlock() return ifname }
34-37
: Lock order is reversed from conventional patternSimilar to the NodeInterface function, the locking pattern is unconventional.
func SetNodeInterface(name string) bool { - defer nodeMu.Unlock() nodeMu.Lock() + defer nodeMu.Unlock() return setNodeInterface(name) }
61-68
: Lock order is reversed from conventional patternSame issue with the lock order in NodeID function.
func NodeID() []byte { - defer nodeMu.Unlock() nodeMu.Lock() + defer nodeMu.Unlock() if nodeID == zeroID { setNodeInterface("") } nid := nodeID return nid[:] }
77-82
: Lock order is reversed from conventional patternSame issue with the lock order in SetNodeID function.
func SetNodeID(id []byte) bool { if len(id) < 6 { return false } - defer nodeMu.Unlock() nodeMu.Lock() + defer nodeMu.Unlock() copy(nodeID[:], id) ifname = "user" return true }vendor/github.com/dgryski/go-farm/Makefile (4)
31-31
: Handle missing VERSION fileThe Makefile reads the version from a VERSION file, but doesn't check if the file exists, which might cause errors during build.
-VERSION=$(shell cat VERSION) +VERSION=$(shell test -f VERSION && cat VERSION || echo "dev")
99-100
: Use safer PIPESTATUS checkingThe current implementation uses PIPESTATUS to check the exit code of the test command, but it might fail in some shell environments.
- tee >(PATH=$(GOPATH)/bin:$(PATH) go-junit-report > target/test/report.xml); \ - test $${PIPESTATUS[0]} -eq 0 + tee >(PATH=$(GOPATH)/bin:$(PATH) go-junit-report > target/test/report.xml); \ + exit_code=$${PIPESTATUS[0]}; \ + test $$exit_code -eq 0 || { echo "Tests failed with exit code $$exit_code"; exit $$exit_code; }
156-158
: Add error handling for godoc serverThe docs target starts a godoc server in the background but doesn't check if it started successfully before attempting to download the documentation.
- nohup sh -c 'GOPATH=$(GOPATH) godoc -http=127.0.0.1:6060' > target/godoc_server.log 2>&1 & + nohup sh -c 'GOPATH=$(GOPATH) godoc -http=127.0.0.1:6060' > target/godoc_server.log 2>&1 & + sleep 2 + if ! curl -s -o /dev/null http://127.0.0.1:6060/; then + echo "Failed to start godoc server, check target/godoc_server.log for details"; exit 1; + fi
167-178
: Update dependency installation to use Go modulesThe current dependency installation uses direct
go get
commands, which is the older approach. Consider updating to use Go modules for better dependency management.deps: - GOPATH=$(GOPATH) go get ./... - GOPATH=$(GOPATH) go get golang.org/x/lint/golint - GOPATH=$(GOPATH) go get github.com/jstemmer/go-junit-report - GOPATH=$(GOPATH) go get github.com/axw/gocov/gocov - GOPATH=$(GOPATH) go get github.com/fzipp/gocyclo - GOPATH=$(GOPATH) go get github.com/gordonklaus/ineffassign - GOPATH=$(GOPATH) go get github.com/client9/misspell/cmd/misspell - GOPATH=$(GOPATH) go get github.com/opennota/check/cmd/structcheck - GOPATH=$(GOPATH) go get github.com/opennota/check/cmd/varcheck - GOPATH=$(GOPATH) go get github.com/kisielk/errcheck - GOPATH=$(GOPATH) go get honnef.co/go/tools/cmd/staticcheck - GOPATH=$(GOPATH) go get github.com/GoASTScanner/gas + go mod download + go install golang.org/x/lint/golint@latest + go install github.com/jstemmer/go-junit-report@latest + go install github.com/axw/gocov/gocov@latest + go install github.com/fzipp/gocyclo@latest + go install github.com/gordonklaus/ineffassign@latest + go install github.com/client9/misspell/cmd/misspell@latest + go install github.com/opennota/check/cmd/structcheck@latest + go install github.com/opennota/check/cmd/varcheck@latest + go install github.com/kisielk/errcheck@latest + go install honnef.co/go/tools/cmd/staticcheck@latest + go install github.com/GoASTScanner/gas@latestvendor/github.com/dgraph-io/ristretto/ring.go (1)
23-27
: Interface design is concise.
A boolean return fromPush([]uint64)
might limit consumer error reporting or partial processing. Consider returning an error if you anticipate more complex handling in the future.vendor/github.com/dgraph-io/ristretto/z/calloc_nojemalloc.go (1)
22-26
: CallocNoRef function.
Returningnil
is acceptable for a no-op version. However, ensure that callers do not rely on an actual allocated slice in this path.vendor/github.com/dgraph-io/ristretto/ttl.go (1)
24-27
: bucketDurationSecs usage.
Consider making this configurable if user requirements change regarding expiration granularity.vendor/github.com/google/uuid/time.go (1)
25-31
: Ensure concurrent UUID generation needs are met.Using a single global
timeMu
lock may limit concurrency when numerous UUIDs need to be generated simultaneously. If high-throughput parallel UUID generation is required, consider using a more scalable mechanism (e.g., sharding locks or eliminating shared mutable state).vendor/github.com/google/uuid/null.go (1)
89-98
: Potential support for 'null' text.Currently, text "null" or empty is parsed by
ParseBytes
which may return an error. If you want to treat "null" literally in text encoding (matching JSON's approach), consider a direct check for"null"
before parsing.vendor/golang.org/x/sys/unix/cap_freebsd.go (2)
55-88
: Consider factoring out shared logic with CapRightsClear.
CapRightsSet
does a thorough job validating version, size, and bit index, but this logic parallels much of what appears inCapRightsClear
. Creating a shared helper could reduce duplication and maintenance overhead.
90-123
: Repeated validation code in CapRightsClear.
As withCapRightsSet
, you might refactor repeated checks (version check, index calculation, etc.) into a small helper function, ensuring consistent validation across both methods.vendor/github.com/dgraph-io/ristretto/sketch.go (3)
38-41
: Consider documenting concurrency requirements for cmSketch.Currently, the
cmSketch
struct does not appear to guard against concurrent reads/writes, which can cause data races if used from multiple goroutines simultaneously. It may help to clarify in the documentation whether the user is expected to synchronize access externally or if concurrency safety is intended in future updates.
57-60
: Use cryptographic randomness if collisions are security-sensitive.Seeding with
rand.NewSource(time.Now().UnixNano())
is fine for general usage, but if collisions or predictability are security concerns, consider using a more secure random source (e.g.,crypto/rand
). Otherwise, please document that standard pseudo-random seeding is intended.
145-156
: Potential edge cases in next2Power.If
numCounters
is very large (close to max int64), shifting might risk overflow. Also, consider how negative inputs should be handled or documented. Otherwise, the bitwise approach here is efficient and standard for rounding to the next power of two.vendor/github.com/dgraph-io/ristretto/z/flags.go (4)
42-47
: Clarify the behavior of default flags vs. user-specified flags.
NewSuperFlagHelp
accepts a defaults string and sets up a map. Consider documenting how flag collisions are handled (e.g., if a user sets a flag again viaFlag()
). This ensures consistent usage patterns for the library’s consumers.
120-123
: Return explicit error rather than calling log.Fatal in library code.The constructor logs fatal errors, which halts the application. In library code, returning errors up the call stack may offer more flexibility for clients to handle failures gracefully.
180-198
: Duration parsing fallback could be more flexible.Currently, if the string contains "d", it interprets it as full days only, otherwise delegates to
time.ParseDuration
. This design is fine, but might surprise users. Consider documenting or expanding the day-notation usage (e.g., "1d12h" might be useful).
283-289
: Warn about potential issues with user.Current in containerized or cross-compiled environments.
user.Current()
can fail in restrictive environments. If it’s a critical path, you might provide a fallback mechanism or at least document the limitation.Would you like a fallback code snippet for these scenarios?
examples/example_ping/main.go (1)
10-29
: Consider adding error handling for all operations.While the code works, it would be better to check for errors after each command operation, not just during client creation.
resp := client.Fire(&wire.Command{Cmd: "PING"}) fmt.Println(resp) resp = client.Fire(&wire.Command{Cmd: "SET", Args: []string{"foo", "bar"}}) fmt.Println(resp) +if resp.Error != "" { + fmt.Printf("Error setting key: %s\n", resp.Error) +} resp = client.Fire(&wire.Command{Cmd: "GET", Args: []string{"foo"}}) fmt.Println(resp) +if resp.Error != "" { + fmt.Printf("Error getting key: %s\n", resp.Error) +} resp = client.Fire(&wire.Command{Cmd: "GET", Args: []string{"foo1"}}) fmt.Println(resp) +if resp.Error != "" { + // This is expected for non-existent keys, could handle differently + fmt.Printf("Key not found: %s\n", resp.Error) +} client.Close()vendor/github.com/google/uuid/CHANGELOG.md (1)
1-42
: Clear and Detailed Changelog Documentation
The changelog is well structured and clearly documents the features and bug fixes introduced in each version (1.6.0, 1.5.0, 1.4.0, and 1.3.1). The commit references and issue links add useful context for future reference.Suggestion: Verify that the formatting of headers (e.g. "## [1.6.0]") remains consistent with your project’s markdown style guidelines.
vendor/github.com/dgraph-io/ristretto/z/calloc_64bit.go (1)
10-15
: Clear Constants Definition for Memory Limits
The constantsMaxArrayLen
andMaxBufferSize
are defined using bit-shift operations, which is a concise and efficient way to represent these values.Suggestion: Consider annotating the inline comments with units (e.g., "bytes") for extra clarity on what these numbers represent.
vendor/github.com/dgraph-io/ristretto/z/calloc_32bit.go (1)
5-7
: Review Build Constraint Formatting
The build constraint is correctly specified; however, there appears to be extra whitespace betweenarmbe
andmips
on line 5.
Suggestion: Normalize the spacing between build tags for consistency (e.g., use a single space between each tag).vendor/golang.org/x/sys/unix/aliases.go (1)
11-16
: Effective Use of Type Aliases for System Call Types
The type aliases forSignal
,Errno
, andSysProcAttr
enhance code clarity by allowing direct usage of these types from thesyscall
package. The build constraints and Go version tags are also appropriately specified.Suggestion: Consider adding brief inline comments explaining the rationale for these aliases, which could help future maintainers.
vendor/github.com/google/uuid/README.md (2)
11-15
: Markdown Heading Level Consistency
The headings for the "Install" and "Documentation" sections are marked as level 6 (######
), which may trigger markdown linting warnings about heading level increments.
Suggestion: Consider using a consistent and slightly higher-level heading (e.g.,## Install
and## Documentation
) to improve readability and adhere to common markdown style guidelines.🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
11-11: Heading levels should only increment by one level at a time
Expected: h2; Actual: h6(MD001, heading-increment)
19-19
: Avoid Bare URLs in Documentation
The documentation includes a bare URL (http://pkg.go.dev/github.com/google/uuid
) which might trigger static analysis warnings.
Suggestion: Replace the bare URL with a proper markdown link, for example:[GoDoc](http://pkg.go.dev/github.com/google/uuid)
, to improve the overall presentation.vendor/github.com/google/uuid/version6.go (1)
15-20
: Minor documentation issues in commentsThere's a small grammatical issue in the function documentation. The sentence "If GetTime fails to return the current NewV6 returns Nil and an error" is a bit unclear - it seems to be missing some words.
vendor/github.com/cespare/xxhash/v2/xxhash_safe.go (1)
1-2
: Consider adding modern build constraint syntax.The file only uses the legacy build tag syntax. For better compatibility with newer Go versions, consider adding the modern
//go:build
syntax.+//go:build appengine // +build appengine
vendor/github.com/dustin/go-humanize/commaf.go (2)
14-20
: Consider not modifying the input parameter.The function modifies the input value with
v.Abs(v)
, which could lead to unexpected behavior if the caller reuses the input after calling this function.func BigCommaf(v *big.Float) string { buf := &bytes.Buffer{} + var absV big.Float if v.Sign() < 0 { buf.Write([]byte{'-'}) - v.Abs(v) + absV.Abs(v) + v = &absV } else { + absV.Set(v) + v = &absV }
30-34
: Avoid adding unnecessary comma only to remove it later.The current implementation always adds a trailing comma in the loop, then truncates it afterward. This works but is slightly inefficient.
- for ; pos < len(parts[0]); pos += 3 { - buf.WriteString(parts[0][pos : pos+3]) - buf.Write(comma) - } - buf.Truncate(buf.Len() - 1) + for ; pos < len(parts[0]); pos += 3 { + buf.WriteString(parts[0][pos : pos+3]) + if pos+3 < len(parts[0]) { + buf.Write(comma) + } + }vendor/github.com/dgraph-io/ristretto/z/file_default.go (1)
27-40
: Error handling is inconsistent in the final step.The function returns detailed error messages for the first three operations, but returns the raw error from Mmap without formatting it consistently with the others.
var err error m.Data, err = Mmap(m.Fd, true, maxSz) // Mmap up to max size. - return err + if err != nil { + return fmt.Errorf("while mmap file: %s, error: %v\n", m.Fd.Name(), err) + } + return nilvendor/golang.org/x/sys/unix/dev_darwin.go (1)
20-24
: Add input validation to Mkdev function.The function does not validate that the major number fits within 8 bits or that the minor number fits within 24 bits, which could lead to unexpected results if invalid values are provided.
func Mkdev(major, minor uint32) uint64 { + // Ensure major fits in 8 bits and minor fits in 24 bits + major &= 0xff + minor &= 0xffffff return (uint64(major) << 24) | uint64(minor) }vendor/golang.org/x/sys/unix/fdset.go (3)
11-13
: Consider adding bounds check for large file descriptorsThe implementation doesn't verify if
fd/NFDBITS
is within the bounds of theBits
array. While this likely works for typical file descriptors, extremely large values could cause an out-of-bounds panic.func (fds *FdSet) Set(fd int) { + if fd < 0 || fd/NFDBITS >= len(fds.Bits) { + return + } fds.Bits[fd/NFDBITS] |= (1 << (uintptr(fd) % NFDBITS)) }
16-18
: Consider adding bounds check for large file descriptorsSimilar to the
Set
method, theClear
method doesn't validate if the array index is within bounds.func (fds *FdSet) Clear(fd int) { + if fd < 0 || fd/NFDBITS >= len(fds.Bits) { + return + } fds.Bits[fd/NFDBITS] &^= (1 << (uintptr(fd) % NFDBITS)) }
21-23
: Consider adding bounds check for large file descriptorsThe
IsSet
method should also include bounds checking to prevent panics with large file descriptors.func (fds *FdSet) IsSet(fd int) bool { + if fd < 0 || fd/NFDBITS >= len(fds.Bits) { + return false + } return fds.Bits[fd/NFDBITS]&(1<<(uintptr(fd)%NFDBITS)) != 0 }vendor/github.com/dustin/go-humanize/.travis.yml (1)
4-14
: Consider updating Go versions in CI configurationThe Travis CI configuration tests against Go versions 1.13.x through 1.16.x, which are now quite old. Consider updating to test with more recent Go versions (e.g., 1.20+).
vendor/github.com/dgryski/go-farm/farmhashmk.go (2)
20-85
: Consider adding comments to explain the algorithm stepsThe
Hash32
function implementation is correct, but the complex bit manipulations, rotations, and magic constants lack explanatory comments that would make the code more maintainable.You could add comments explaining:
- The purpose of constants like
c1
,c2
, and0xe6546b64
- The different steps of the algorithm
- The reasoning behind the specific bit manipulations and rotations
15-16
: Simplify slice expression for better readabilityThe slice access pattern
s[0 : 0+4]
could be simplified to the more readables[0:4]
.- a += binary.LittleEndian.Uint32(s[0 : 0+4]) + a += binary.LittleEndian.Uint32(s[0:4])vendor/github.com/dustin/go-humanize/ftoa.go (2)
40-43
: Consider adding support for special float valuesThe current implementation uses a fixed precision of 6 decimal places which may not be suitable for very large or small numbers. It also doesn't explicitly handle special float values like NaN or Infinity.
// Ftoa converts a float to a string with no trailing zeros. func Ftoa(num float64) string { + // Handle special values like NaN and Infinity + if math.IsNaN(num) { + return "NaN" + } + if math.IsInf(num, 1) { + return "+Inf" + } + if math.IsInf(num, -1) { + return "-Inf" + } return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64)) }
45-49
: Same special case handling needed for FtoaWithDigitsSimilar to Ftoa, this function should handle special float values like NaN and Infinity.
// FtoaWithDigits converts a float to a string but limits the resulting string // to the given number of decimal places, and no trailing zeros. func FtoaWithDigits(num float64, digits int) string { + // Handle special values like NaN and Infinity + if math.IsNaN(num) { + return "NaN" + } + if math.IsInf(num, 1) { + return "+Inf" + } + if math.IsInf(num, -1) { + return "-Inf" + } return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits)) }vendor/golang.org/x/sys/unix/race.go (1)
15-31
: Race detection wrappers implemented correctlyThese internal functions correctly wrap the runtime's race detection functionality for use within the unix package. Consider adding documentation comments for maintainability, even though they're not exported functions.
const raceenabled = true +// raceAcquire marks the beginning of a critical section by recording that +// the current goroutine has acquired the lock at addr. func raceAcquire(addr unsafe.Pointer) { runtime.RaceAcquire(addr) } +// raceReleaseMerge marks the end of a critical section by recording that +// the current goroutine has released the lock at addr. func raceReleaseMerge(addr unsafe.Pointer) { runtime.RaceReleaseMerge(addr) } +// raceReadRange marks a read operation on memory range [addr, addr+len). func raceReadRange(addr unsafe.Pointer, len int) { runtime.RaceReadRange(addr, len) } +// raceWriteRange marks a write operation on memory range [addr, addr+len). func raceWriteRange(addr unsafe.Pointer, len int) { runtime.RaceWriteRange(addr, len) }vendor/github.com/dustin/go-humanize/big.go (1)
21-31
: Similar potential overflow issue in the unlimited order of magnitude functionThe implementation of
oom
function is correct for calculating the order of magnitude without an upper limit. However, it has the same potential issue with the return value calculation as theoomm
function.For more precise decimal representation of large integers, consider using the
Rat
type from themath/big
package:func oom(n, b *big.Int) (float64, int) { mag := 0 m := &big.Int{} for n.Cmp(b) >= 0 { n.DivMod(n, b, m) mag++ } - return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag + // Create a more precise representation for the fraction part + rat := new(big.Rat).SetFrac(m, b) + f, _ := rat.Float64() + return float64(n.Int64()) + f, mag }vendor/github.com/pkg/errors/Makefile (3)
13-16
: Consider updating the staticcheck installation methodThe current method of installing staticcheck is outdated. The repository has moved to a new location and the installation method has changed.
staticcheck: - $(GO) get honnef.co/go/tools/cmd/staticcheck + $(GO) install honnef.co/go/tools/cmd/staticcheck@latest staticcheck -checks all $(PKGS)You can verify this by checking the current installation method:
#!/bin/bash # Check the current recommended installation method for staticcheck curl -s https://staticcheck.io/docs/getting-started/ | grep -A 5 "Installation"
17-23
: Ensure misspell configuration is appropriateThe misspell configuration is using GB locale which might not be appropriate depending on your project's audience. Consider whether US English might be more suitable.
24-27
: Consider updating Go tool installation methodsThe installation methods for several Go tools (unconvert, ineffassign, unparam, errcheck) use the older
go get
approach. Modern Go projects typically usego install
with versioning.For example:
unconvert: - $(GO) get github.com/mdempsky/unconvert + $(GO) install github.com/mdempsky/unconvert@latest unconvert -v $(PKGS)Apply similar changes to other tool installations.
Also applies to: 28-31, 34-37, 38-41
vendor/golang.org/x/sys/unix/dev_freebsd.go (1)
26-30
: Check for potential overflow.
Combining major and minor by shifting major left by 8 bits might overflow ifminor
can occupy more than 8 bits. Ensure calling code uses valid ranges.Change the doc comment to clarify that
minor
must fit within 8 bits for correct behavior, for example:-// Mkdev returns a FreeBSD device number generated from the given major and -// minor components. +// Mkdev returns a FreeBSD device number from the given major and minor +// components. Note that minor must fit within 8 bits to avoid overflow.vendor/golang.org/x/sys/unix/mkall.sh (3)
53-53
: Fix potential word splitting issue in docker run command.The command substitution
$(cd -- "$(dirname -- "$0")/.." && pwd)
should be quoted to prevent word splitting if paths contain spaces.-$cmd docker run --interactive --tty --volume $(cd -- "$(dirname -- "$0")/.." && pwd):/build generate:$GOOS +$cmd docker run --interactive --tty --volume "$(cd -- "$(dirname -- "$0")/.." && pwd)":/build generate:$GOOS🧰 Tools
🪛 Shellcheck (0.10.0)
[warning] 53-53: Quote this to prevent word splitting.
(SC2046)
59-62
: Pattern matching redundancy in case statement.The pattern
_* | *_ | _
contains redundant parts as_
will never be matched due to the preceding patterns.-case "$GOOSARCH" in -_* | *_ | _) +case "$GOOSARCH" in +_* | *_)🧰 Tools
🪛 Shellcheck (0.10.0)
[warning] 59-59: This pattern always overrides a later one on line 59.
(SC2221)
[warning] 59-59: This pattern always overrides a later one on line 59.
(SC2221)
[warning] 59-59: This pattern never matches because of a previous pattern on line 59.
(SC2222)
233-235
: Fix quoting in echo statement for AIX build.The
"$GOOSARCH"
in the echo statement is improperly quoted, which actually unquotes the variable. Use consistent quoting style.- echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ; + echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_${GOOSARCH}_gccgo.go && gofmt -w zsyscall_${GOOSARCH}_gc.go" ;🧰 Tools
🪛 Shellcheck (0.10.0)
[warning] 234-234: The surrounding quotes actually unquote this. Remove or escape them.
(SC2027)
[warning] 234-234: The surrounding quotes actually unquote this. Remove or escape them.
(SC2027)
vendor/golang.org/x/sys/unix/README.md (6)
3-4
: Fix bare URL in documentation.Replace the bare URL with a proper Markdown link format for better readability and to follow Markdown best practices.
-The sys/unix package provides access to the raw system call interface of the -underlying operating system. See: https://godoc.org/golang.org/x/sys/unix +The sys/unix package provides access to the raw system call interface of the +underlying operating system. See: [sys/unix documentation](https://godoc.org/golang.org/x/sys/unix)🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
4-4: Bare URL used
null(MD034, no-bare-urls)
12-13
: Minor grammatical improvement.Add a comma before "so" when connecting two independent clauses.
-There are currently two ways we generate the necessary files. We are currently -migrating the build system to use containers so the builds are reproducible. +There are currently two ways we generate the necessary files. We are currently +migrating the build system to use containers, so the builds are reproducible.🧰 Tools
🪛 LanguageTool
[uncategorized] ~13-~13: Use a comma before ‘so’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...ating the build system to use containers so the builds are reproducible. This is be...(COMMA_COMPOUND_SENTENCE_2)
45-45
: Fix terminology consistency.Use "OS-specific" with a hyphen for consistency when used as a modifier.
-The OS specific files for the new build system are located in the `${GOOS}` +The OS-specific files for the new build system are located in the `${GOOS}`🧰 Tools
🪛 LanguageTool
[uncategorized] ~45-~45: When ‘OS-specific’ is used as a modifier, it is usually spelled with a hyphen.
Context: ...s has installed on their computer. The OS specific files for the new build system are loca...(SPECIFIC_HYPHEN)
48-48
: Fix verb spelling.The word "checkout" as a verb should be spelled with a space.
-`${GOOS}/Dockerfile` to checkout the new release of the source. +`${GOOS}/Dockerfile` to check out the new release of the source.🧰 Tools
🪛 LanguageTool
[grammar] ~48-~48: The word “checkout” is a noun. The verb is spelled with a white space.
Context: ...e Dockerfile at${GOOS}/Dockerfile
to checkout the new release of the source. To buil...(NOUN_VERB_CONFUSION)
69-73
: Add language identifier to code block.Specify a language for the fenced code block to enable proper syntax highlighting.
-``` +```go func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)<details> <summary>🧰 Tools</summary> <details> <summary>🪛 markdownlint-cli2 (0.17.2)</summary> 69-69: Fenced code blocks should have a language specified null (MD040, fenced-code-language) </details> </details> --- `177-179`: **Fix grammar in description.** Correct the noun agreement in "syscall number" to "syscall numbers". ```diff -A list of numeric constants for all the syscall number of the specific GOOS +A list of numeric constants for all the syscall numbers of the specific GOOS and GOARCH. Generated by mksysnum (see above).
🧰 Tools
🪛 LanguageTool
[uncategorized] ~178-~178: The grammatical number of this noun doesn’t look right. Consider replacing it.
Context: ...f numeric constants for all the syscall number of the specific GOOS and GOARCH. Genera...(AI_EN_LECTOR_REPLACEMENT_NOUN_NUMBER)
vendor/github.com/dgraph-io/ristretto/z/mmap_linux.go (2)
57-66
: Validate choice of MADV advice.
Selectingunix.MADV_RANDOM
for random reads is fine, but you might also consider advanced flags such asunix.MADV_SEQUENTIAL
orunix.MADV_DONTNEED
for other known access patterns to optimize page management further.
68-71
: Consider usage of asynchronous sync.
Msync
withunix.MS_SYNC
blocks until the sync completes. If you prefer better performance and can tolerate some delay,unix.MS_ASYNC
might be more suitable, with an explicit sync only if needed.vendor/github.com/dgraph-io/ristretto/README.md (3)
19-19
: Refine wording for brevity.
The repeated phrase "a variety of" in lines 19, 120, and 128 can be reduced for more concise communication. Consider removing or replacing with succinct alternatives like "several" or "multiple."- we use a variety of techniques for managing contention + we use multiple techniques for managing contention - The reason this is a Config flag is because there's ... + The reason this is a Config flag is that there's ... - Ristretto has a variety of defaults ... + Ristretto has multiple defaults ...Also applies to: 120-120, 128-128
🧰 Tools
🪛 LanguageTool
[style] ~19-~19: The phrase “a variety of” may be wordy. To make your writing clearer, consider replacing it.
Context: ...ounter). * Fast Throughput - we use a variety of techniques for managing contention and ...(A_VARIETY_OF)
23-23
: Address punctuation and informal wording.
Minor punctuation and style tweaks can improve clarity. For example:
- Insert commas before "and" when connecting independent clauses.
- Replace informal "anyways" with "anyway."
- Insert missing articles like "the."
- figure out your ideal `Config` values and you're off and running. + figure out your ideal `Config` values, and you're off and running. - Ristretto is production-ready. See [Projects using Ristretto]. + Ristretto is production-ready. See [the Projects using Ristretto]. - If for some reason you see Get performance decreasing + If, for some reason, you see Get performance decreasing - and you don't want to waste time on items that will be dropped anyways). + and you don't want to waste time on items that will be dropped anyway). - otherwise just fill the `uint64` at the `0` position and it will behave + otherwise just fill the `uint64` at the `0` position, and it will behaveAlso applies to: 26-26, 116-116, 131-131, 138-139
🧰 Tools
🪛 LanguageTool
[uncategorized] ~23-~23: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...st figure out your idealConfig
values and you're off and running. ## Status Ris...(COMMA_COMPOUND_SENTENCE)
106-106
: Review plural usage, hyphens, and prepositions.
- If a cost is “1,” phrase it “if cost is 1, it increases the total to…”
- Use “full of” instead of “full with.”
- Hyphenate “one-hour period.”
- Replace “were ran” with “were run.”
- Replace “make it in the cache” with “make it into the cache.”
- a cost of 1 increases total cache cost to 101 + a cost of 1 increases the total cache cost to 101 - if the cache is full with 1,000 1KB items + if the cache is full of 1,000 1KB items - references to a CODASYL database for a one hour period. + references to a CODASYL database for a one-hour period. - All throughput benchmarks were ran on an Intel Core ... + All throughput benchmarks were run on an Intel Core ... - the most popular items to be Set multiple times and eventually make it in the cache. + the most popular items to be Set multiple times and eventually make it into the cache.Also applies to: 108-108, 180-180, 189-189, 225-225
🧰 Tools
🪛 LanguageTool
[grammar] ~106-~106: Please verify that the plural noun “increases” is in agreement with the quantifier “1”. Did you mean to use the singular form?
Context: ...st is 100 and a new item with a cost of 1 increases total cache cost to 101, 1 item will be...(ONE_PLURAL)
[uncategorized] ~106-~106: You might be missing the article “the” here.
Context: ...d a new item with a cost of 1 increases total cache cost to 101, 1 item will be evict...(AI_EN_LECTOR_MISSING_DETERMINER_THE)
vendor/golang.org/x/sys/unix/asm_linux_amd64.s (2)
23-37
: Ensure consistent usage of entersyscall/exitsyscall.
These calls safeguard the runtime’s scheduler during blocking system calls. Verify that concurrency assumptions hold true across the calling code, especially if you’re mixing with goroutines expecting non-blocking I/O.
44-56
: Consider reusing entersyscall/exitsyscall forRawSyscallNoError
.
If a syscalls can block, ignoring the runtime’s scheduler might lead to unexpected scheduling delays. Evaluate whether you want minimal overhead or safe concurrency.vendor/github.com/google/uuid/version7.go (2)
11-14
: Refine the documentation to remove redundancy.There's a redundant phrase in the comment describing the Unix Epoch timestamp. Consider removing the extra "seconds" for clarity.
-// the number of milliseconds seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. +// the number of milliseconds since midnight 1 Jan 1970 UTC, leap seconds excluded.
86-86
: Correct the spelling.There's a minor typo in the comment. "guarenteed" should be "guaranteed."
-// The returned (milli << 12 + seq) is guarenteed to be greater... +// The returned (milli << 12 + seq) is guaranteed to be greater...vendor/github.com/cespare/xxhash/v2/README.md (1)
31-41
: Consider adding a comma in the compatibility section.The sentence in line 33 might be clearer with a comma after "module".
-This package is in a module and the latest code is in version 2 of the module. +This package is in a module, and the latest code is in version 2 of the module.🧰 Tools
🪛 LanguageTool
[uncategorized] ~33-~33: Possible missing comma found.
Context: ... ## Compatibility This package is in a module and the latest code is in version 2 of ...(AI_HYDRA_LEO_MISSING_COMMA)
vendor/github.com/dustin/go-humanize/number.go (2)
59-59
: Add missing quote in comment.There's a missing closing quote after the format string in the comment, which may cause confusion.
Apply this diff to complete the quoted string:
-// "#.###,###### => 12.345,678900 +// "#.###,######" => "12.345,678900"
114-114
: Consider returning an error instead of panicking.Panicking may abruptly terminate the calling program when an invalid positive sign directive is encountered. For a library function, returning an error often provides users more control over error handling.
For example:
-if format[formatIndx[0]] != '+' { - panic("RenderFloat(): invalid positive sign directive") -} +if format[formatIndx[0]] != '+' { + return "[invalid sign directive]" +}vendor/golang.org/x/sys/unix/asm_linux_loong64.s (1)
54-55
: Missing newline at end of fileThe file is missing a newline character at the end, which could potentially cause issues with some tools.
Add a newline at the end of the file to comply with standard file formatting practices.
vendor/github.com/dgraph-io/ristretto/z/mmap_unix.go (1)
28-56
: Consider adding more documentation for error conditionsWhile the implementation is correct, the documentation could be enhanced to describe potential error conditions for each function, making it easier for users to handle errors appropriately.
Add more detailed documentation about potential error conditions for each function. For example:
// Mmap uses the mmap system call to memory-map a file. If writable is true, // memory protection of the pages is set so that they may be written to as well. +// +// Potential errors: +// - If fd is invalid +// - If size is negative +// - If the underlying mmap system call fails due to permissions or resource limits func mmap(fd *os.File, writable bool, size int64) ([]byte, error) {vendor/github.com/dgryski/go-farm/farmhashcc.go (6)
30-40
: Reduce repeated mixing for short slices if performance is critical.
hash32Len0to4
repeatedly mixes data in a small loop for slices up to 4 bytes. Although this logic is likely derived from CityHash semantics, you could inline or simplify for slices of length 1, 2, 3, or 4 to reduce overhead.
53-56
: Struct naming clarity.
type uint128 struct
is straightforward, but consider clarifying the type name to represent that it’s a higher-level data structure (e.g.,type Uint128 struct
) unless you want to keep it intentionally minimal. The all-lowercase name might be less idiomatic in Go.
60-96
: Potential performance trade-offs in cityMurmur.
cityMurmur
processes data in chunks with multiple 64-bit reads, bit rotations, and repeated mixing. While correct for a reference implementation, you may gain further speed by unrolling the loop or inlining small-slice logic. Check hardware metrics to confirm necessity.
179-183
: Public function usage clarity.
Fingerprint128
returns twouint64
values(lo, hi)
, requiring callers to combine them for a full 128-bit representation. Ensure this usage is well-documented so consumers of your API handle it correctly.
185-188
: Alias vs. direct call.
Hash128
just callsFingerprint128
. This is okay but slightly redundant. If you foresee additional logic or naming distinctions, keep it. Otherwise, you might unify them and document accordingly.
190-194
: Provide rationale for seeded vs. unseeded.
Hash128WithSeed
follows the same hashing path but allows for custom seeds. Document expected use cases where users might choose seeded vs. unseeded variants, such as partitioning hashes or personalizing hash outputs.vendor/github.com/dgryski/go-farm/farmhashuo.go (3)
8-13
: Rotate-based mixing mechanism.
uoH
uses an additional rotate (bits.RotateLeft64
) with a negative integer. This is valid in Go (rotating right if the shift is negative), but it may be less immediately intuitive. Keep it if matching upstream code, but do comment for maintainers.
108-114
: Code duplication with single seed.
Hash64WithSeed
callsnaHash64WithSeed
for lengths ≤ 64, then delegates toHash64WithSeeds
with a forced zero forseed0
. This duplication is normal if adapting from separate references, but consider combining the logic for easier maintainability.
116-122
: Clarify usage of default seeds.
uoHash64
uses hardcoded seeds81
and0
for lengths > 64. Make sure this is documented as the “default” approach and that callers are aware it can’t be influenced from outside. If users need more control, propose or plan an exported function that leverages different seeds.vendor/golang.org/x/sys/unix/asm_linux_386.s (1)
59-61
: Transparent jump to socketcall.
TEXT ·socketcall(SB)
jumps tosyscall·socketcall(SB)
. This matches the approach of hooking socket calls in a single place. Double-check each indirect jump is tested in context, especially around concurrency or partial reads/writes.main.go (4)
26-28
:mu
is unused.
The static analysis hints indicate that themu
(RWMutex) field is never used. Either remove it or use it for any shared state that might still require locking, to avoid code bloat.type Client struct { id string conn net.Conn watchConn net.Conn watchCh chan *wire.Response host string port int lcache *ristretto.Cache - mu sync.RWMutex // Mutex for thread-safe operations wg sync.WaitGroup }
🧰 Tools
🪛 golangci-lint (1.64.8)
27-27: field
mu
is unused(unused)
54-62
: Ristretto cache initialization looks good.
You might consider makingNumCounters
,MaxCost
, andBufferItems
configurable to support different environments or memory constraints. Doing so can help users fine-tune caching for large or small workloads.
80-86
: Consider adding a graceful shutdown mechanism for the goroutine.
The goroutine that callsListenForMessages
may run indefinitely. You currently rely onc.wg.Wait()
inClose()
, but you might also want a context-based stop signal to avoid blocking if the connection is disrupted or if the user wants early termination.
220-244
:ListenForMessages
panics on watch connection errors.
A panic might bring the entire service down. If you want to keep the client robust, consider more graceful error handling (return an error to the caller, log it, or attempt reconnection).vendor/golang.org/x/sys/unix/epoll_zos.go (1)
161-203
:epollwait
usage of a fixed-size slice, then appending, might cause confusion.
You start withpollfds := make([]PollFd, 4)
then append to it in a loop, effectively skipping the initial pre-allocated elements. Switching tomake([]PollFd, 0, 4)
can be cleaner:-func (e *epollImpl) epollwait(epfd int, events []EpollEvent, msec int) (n int, err error) { - pollfds := make([]PollFd, 4) + pollfds := make([]PollFd, 0, 4)vendor/golang.org/x/sys/unix/fstatfs_zos.go (2)
16-31
: Ensure error handling consistency inFstatfs
function.
While the core logic appears sound, consider wrapping the post-call assignment ofstat_xx
fields in a separate function or block. This could make the code more maintainable and reduce risk of missing future fields if the system structure changes.
32-56
: Consider refactoring the pass loop for clarity.
Using afor
loop with an index from 0 to 4 is clear, but employing a switch plus multiplebreak
statements might obscure the intent. A refactored approach (e.g., slice of function references) can reduce branching and repetition.-func Fstatfs(fd int, stat *Statfs_t) (err error) { ... - for passn := 0; passn < 5; passn++ { - switch passn { - case 0: - err = tryGetmntent64(stat) - break - case 1: - err = tryGetmntent128(stat) - break - ... - } - if err == nil || (err != nil && err != ERANGE) { - break - } - } +func Fstatfs(fd int, stat *Statfs_t) error { + ... + attempts := []func(*Statfs_t) error{ + tryGetmntent64, + tryGetmntent128, + tryGetmntent256, + tryGetmntent512, + tryGetmntent1024, + } + for _, attempt := range attempts { + err = attempt(stat) + if err == nil || (err != ERANGE && err != nil) { + break + } + } ... }vendor/golang.org/x/sys/unix/syscall_aix_ppc.go (1)
39-53
: Consider unified error handling for file status calls.
All wrappers (Fstat
,Fstatat
,Lstat
,Stat
) directly call their respective syscalls with minimal error handling. If multiple error transformations or special cases arise in AIX environments, a shared function could unify handling.vendor/golang.org/x/sys/unix/ioctl_unsigned.go (2)
49-58
: Guard against potential integer overflow inIoctlGetInt
.
If the ioctl returns large numbers, storing them in a Goint
might truncate on some platforms. Confirm that all known request codes remain within the permissible range ofint
.Do you want me to generate a check for unexpected large return values?
60-70
: Consider inlining specialized request codes forIoctlGetWinsize
andIoctlGetTermios
.
Similar to the TODO inIoctlSetWinsize
andIoctlSetTermios
, if these are known to only handle certain request codes (e.g.,TIOCGWINSZ
), referencing them directly can reduce confusion and potential misuse.vendor/github.com/google/uuid/hash.go (1)
28-43
: Consider validating the hash length before copying.While most hashing algorithms used here (e.g., MD5, SHA1) naturally produce at least 16 bytes, the function documentation states that the hash “should be at least 16 bytes in length” but doesn't enforce it. If a non-standard or insufficient hash were mistakenly used, copying fewer bytes could lead to incorrect UUID values.
vendor/golang.org/x/sys/unix/ioctl_zos.go (2)
27-31
: Window size configuration via ioctl is fine.Hardcoding
TIOCSWINSZ
forreq
could simplify usage in the future once any backward-compatibility concerns are resolved.
65-72
: Terminal attributes retrieval logic looks good.The check for
TCGETS
is correctly enforced before callingTcgetattr
. Optionally, consider usingruntime.KeepAlive(&value)
for consistency, though typically reading from the kernel is completed once the syscall returns.vendor/github.com/pkg/errors/errors.go (1)
181-197
: Additional context with stack trace wrapping.Wrapping an error with both a new message and stack trace is helpful. However, consider if a typical usage might overlap with the Go 1.13+
%w
approach infmt.Errorf
.vendor/github.com/dgraph-io/ristretto/z/bbloom.go (1)
101-108
: Note about element count trackingThe
ElemNum
field is incremented for each bit set in theAdd
method rather than once per hash added. This could lead to overcounting if this field is used to track the number of unique elements added to the Bloom filter.Consider incrementing
ElemNum
only once per hash addition:func (bl *Bloom) Add(hash uint64) { h := hash >> bl.shift l := hash << bl.shift >> bl.shift for i := uint64(0); i < bl.setLocs; i++ { bl.Set((h + i*l) & bl.size) - bl.ElemNum++ } + bl.ElemNum++ }vendor/github.com/dgraph-io/ristretto/z/z.go (1)
33-57
: Consider returning errors instead of panickingThe
KeyToHash
function panics for unsupported key types. While this may be a deliberate design choice, consider returning error values instead to allow callers to handle type errors gracefully in production environments.-func KeyToHash(key interface{}) (uint64, uint64) { +func KeyToHash(key interface{}) (uint64, uint64, error) { if key == nil { - return 0, 0 + return 0, 0, nil } switch k := key.(type) { case uint64: - return k, 0 + return k, 0, nil case string: - return MemHashString(k), xxhash.Sum64String(k) + return MemHashString(k), xxhash.Sum64String(k), nil // ... other cases ... default: - panic("Key type not supported") + return 0, 0, fmt.Errorf("key type %T not supported", key) } }vendor/github.com/dgraph-io/ristretto/z/btree.go (3)
259-261
: Access restriction on invalid keys.
Panicking whenk
is0
ormath.MaxUint64
ensures reserved key space, but it forces the entire application to crash on misuse. Consider returning an error for these edge cases instead of panicking.
263-278
: Potential root node expansion edge case.
Whenroot.isFull()
triggers a split, the code reuses node references. Frequent root splits in rapid succession might lead to repeated buffer growth. Consider caching or reusing buffer segments to reduce allocations.
315-317
: Remove or document unused code.
TheshareWithSiblingXXX
function is commented out and marked unused. Remove it or provide usage context to avoid confusion and keep the codebase clean.vendor/golang.org/x/sys/unix/affinity_linux.go (1)
63-68
: Spark warnings on out-of-bounds CPU clearing.
Wheni >= len(s)
, the code silently fails to clear the CPU bit. Consider logging a warning or returning an error, so that misconfigurations do not go unnoticed.vendor/github.com/pkg/errors/stack.go (2)
65-84
: Consider cost of detailed stack traces in high-frequency use.
Frame.Format
processes function/file/line for each frame. In performance-sensitive paths or tight loops, repeated calls toruntime.FuncForPC
can be expensive. Consider caching or deferring the resolution if profiling indicates high overhead.
108-116
: Refrain from printing partial stack traces by default.
Using+v
can generate extensive multi-line output. If too verbose, consider a short summary or a configurable detail level—particularly important if logs might become noisy in production.vendor/golang.org/x/sys/unix/sockcmsg_unix.go (1)
38-53
: Suggest testing for partial/truncated message scenarios.
While this parsing logic is correct and idiomatic, it would be beneficial to add unit tests that verify behavior when the byte slice is truncated or partially contains control message data. This helps ensure graceful error handling and prevents any unsafe corner cases.vendor/github.com/dgraph-io/ristretto/z/file.go (2)
36-36
: Minor naming note.
The global variableNewFile
is used as a sentinel error rather than a function. Consider renaming it (e.g.,ErrNewFile
) for clarity, to better match Go error variable naming conventions.
166-184
: Good cleanup sequence on Delete.
Unmapping before truncation and file removal helps avoid stray references to stale memory. This function is consistent with well-managed file resources, though be mindful of concurrency if multiple goroutines interact with the file concurrently.vendor/github.com/dgraph-io/ristretto/z/histogram.go (2)
37-46
: Consider validating input for Fibonacci generation.
Currently, the function only assertsnum > 4
. If a smaller number is passed, the function panics. You might consider returning an error or handling it gracefully to maintain production-grade reliability.
169-192
: Enforce validity ofp
inPercentile
.
Though the doc statesp
must be [0.0 - 1.0], no explicit check is implemented. CallingPercentile(2.0)
or a negative p might not produce meaningful results.Consider:
func (histogram *HistogramData) Percentile(p float64) float64 { + if p < 0 || p > 1 { + return 0 // or histogram.Bounds[0], or an error + } ...vendor/github.com/google/uuid/uuid.go (1)
164-172
: Panic-based error handling.
MustParse
panics if parsing fails, which may or may not be desired in production code. This is commonly acceptable for initialization flows, though.vendor/github.com/dgraph-io/ristretto/z/allocator.go (2)
181-194
: Check partial trim behavior.
TrimTo
frees entire buffers only after crossingmax
. Ifalloc
is huge, the leftover could be large. This is presumably intended, but confirm if partial buffer trimming was required.
224-237
:AllocateAligned
zeroes memory forcibly.
This is good for safety, but can introduce overhead for large allocations. Evaluate performance trade-offs if this is called frequently.vendor/golang.org/x/sys/unix/syscall_aix.go (1)
330-333
: Implement or remove the unimplementedsendfile
function.
Currently,sendfile
returnsENOSYS
and is marked with aTODO
; you might consider either implementing it if the underlying AIX syscall becomes available or removing it if it is not planned for future use.Do you want me to open a tracking issue or provide a fallback approach for file transfers on AIX?
vendor/github.com/dgraph-io/ristretto/z/buffer.go (1)
58-73
: Consider providing an error return instead of panicking on allocation failures.
This constructor panics ifCalloc
or file operations fail. Depending on usage, returning an error can be more flexible than panicking in library code.-func NewBuffer(capacity int, tag string) *Buffer { +func NewBuffer(capacity int, tag string) (*Buffer, error) { ... - panic(err) + return nil, err }vendor/github.com/dgraph-io/ristretto/policy.go (1)
134-208
: Avoid potential linear scans insampledLFU
under high load.
When evicting items,fillSample
scans potentially many entries. Under high or skewed workloads, consider a more efficient data structure (e.g., random indexing or min-heap) to reduce eviction overhead and improve throughput.vendor/github.com/dgraph-io/ristretto/store.go (4)
24-30
: Consider mergingstoreItem
withItem
.There's a TODO comment questioning the need for a separate
storeItem
struct. If the fields align closely withItem
, merging them might reduce duplicated definitions and simplify maintenance.
70-79
: Parameterize the number of shards.
numShards
is currently a fixed constant (256). Making this configurable could help adapt to different workloads or hardware environments while retaining the benefits of sharding.
129-145
: Remove expired items eagerly to free up memory.While returning
false
for expired entries prevents stale reads, it leaves the items in the map untilCleanup
runs. Consider removing them immediately to conserve memory and reduce potential collisions in high-churn scenarios.
229-242
: Handle eviction failures gracefully.
Clear
performs eviction callbacks under a single lock and doesn't accommodate partial failures. IfonEvict
encounters errors, consider adding an error-handling mechanism or partial rollback strategy.vendor/golang.org/x/sys/unix/ioctl_linux.go (1)
108-148
: Ensure safe handling of dedupe range buffers.Manual construction of the buffer for
IoctlFileDedupeRange
is prone to out-of-bounds or alignment mistakes. Regularly review and test these bounds for different platforms to avoid memory corruption issues.vendor/golang.org/x/sys/unix/syscall_bsd.go (1)
599-603
: Offer help with the TODO calls.There is a
TODO
indicating additional calls (e.g.,Acct
,Gethostuuid
,Ptrace
) may need wrapping. Let me know if you'd like assistance creating appropriate Go wrappers for these system calls.vendor/github.com/dgraph-io/ristretto/cache.go (3)
34-37
: Consider makingsetBufSize
configurable.Hardcoding
setBufSize = 32 * 1024
can limit flexibility under different workloads. A configurable option inConfig
(or an environment variable) might better accommodate varying usage patterns and reduce the risk of either excessive memory usage or dropped sets under high contention.-var ( - // TODO: find the optimal value for this or make it configurable - setBufSize = 32 * 1024 -) +const DefaultSetBufSize = 32768 + +// In NewCache or Config, allow override via config.SetBufSize if needed. +// Example: +// if config.SetBufSize > 0 { +// setBufSize = config.SetBufSize +// }
83-140
: Gracefully handle negative configuration values.Although zero values for
NumCounters
,MaxCost
,BufferItems
are checked, negative integers are not explicitly handled. Passing a negative value may introduce unexpected behavior or overflow in some logic.switch { case config.NumCounters <= 0: return nil, errors.New("NumCounters must be positive") case config.MaxCost <= 0: return nil, errors.New("MaxCost must be positive") case config.BufferItems <= 0: return nil, errors.New("BufferItems must be positive") ... }
429-503
: MakenumToKeep
configurable to avoid excessive memory usage.In
processItems()
,numToKeep
is hardcoded to100000
. Large traffic or extended runtimes may cause significant memory usage instartTs
. Exposing it as a configurable parameter can optimize memory usage, especially under varying traffic patterns.- numToKeep := 100000 // TODO: Make this configurable via options. + numToKeep := config.AdmissionTrackingLimit + if numToKeep <= 0 { + numToKeep = 100000 // fallback if not set + }vendor/github.com/dgraph-io/ristretto/z/simd/baseline.go (3)
10-20
: Check for out-of-bounds access and clarify stepping logic.The
Naive
function incrementsi
by 2 in each iteration, but there's no boundary check before accessingxs[i]
. If the slice has an odd length, this could lead to an out-of-bounds error.Additionally, the function appears to be designed for a specific data structure where elements are stored at even indices. Consider adding a comment explaining why the function steps by 2 and why the result is divided by 2.
// Search finds the key using the naive way func Naive(xs []uint64, k uint64) int16 { var i int - for i = 0; i < len(xs); i += 2 { + for i = 0; i < len(xs)-1; i += 2 { x := xs[i] if x >= k { return int16(i / 2) } } return int16(i / 2) }
92-99
: Clarify the Binary search implementation.The
Binary
function uses a multiplication by 2 to access elements, similar to other functions in this file. This suggests a specific data structure pattern, but it's not clearly explained.Also, there's a boundary check
if i*2 >= len(keys)
but its purpose isn't obvious without more context.func Binary(keys []uint64, key uint64) int16 { + // This binary search is designed for a specific data structure + // where keys are stored at even indices (0, 2, 4, etc.) return int16(sort.Search(len(keys), func(i int) bool { if i*2 >= len(keys) { return true } return keys[i*2] >= key })) }
101-130
: Review unused comparison functions for consistency.The three comparison functions are marked as unused and have inconsistent behavior:
cmp2_native
checks for equality (==)cmp4_native
checks for greater than or equal (>=)cmp8_native
only compares against pk[0]If these functions are intended for future use, they should have consistent behavior and better documentation.
Consider either:
- Removing these unused functions if they're not needed
- Making their behavior consistent and adding proper documentation
- Implementing tests to verify their correctness if they will be used
//nolint:unused func cmp2_native(twos, pk [2]uint64) int16 { + // Returns the index of the first element that matches the key + // or 2 if no match is found if twos[0] == pk[0] { return 0 } if twos[1] == pk[1] { return 1 } return 2 } //nolint:unused func cmp4_native(fours, pk [4]uint64) int16 { + // Returns the index of the first element that is >= the corresponding key + // or 4 if no such element is found for i := range fours { if fours[i] >= pk[i] { return int16(i) } } return 4 } //nolint:unused func cmp8_native(a [8]uint64, pk [4]uint64) int16 { + // Returns the index of the first element that is >= pk[0] + // or 8 if no such element is found for i := range a { if a[i] >= pk[0] { return int16(i) } } return 8 }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
go.sum
is excluded by!**/*.sum
📒 Files selected for processing (190)
examples/example_ping/main.go
(1 hunks)go.mod
(1 hunks)main.go
(6 hunks)vendor/github.com/cespare/xxhash/v2/.travis.yml
(1 hunks)vendor/github.com/cespare/xxhash/v2/LICENSE.txt
(1 hunks)vendor/github.com/cespare/xxhash/v2/README.md
(1 hunks)vendor/github.com/cespare/xxhash/v2/xxhash.go
(1 hunks)vendor/github.com/cespare/xxhash/v2/xxhash_amd64.go
(1 hunks)vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s
(1 hunks)vendor/github.com/cespare/xxhash/v2/xxhash_other.go
(1 hunks)vendor/github.com/cespare/xxhash/v2/xxhash_safe.go
(1 hunks)vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/.go-version
(1 hunks)vendor/github.com/dgraph-io/ristretto/.golangci.yml
(1 hunks)vendor/github.com/dgraph-io/ristretto/CHANGELOG.md
(1 hunks)vendor/github.com/dgraph-io/ristretto/LICENSE
(1 hunks)vendor/github.com/dgraph-io/ristretto/README.md
(1 hunks)vendor/github.com/dgraph-io/ristretto/cache.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/policy.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/ring.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/sketch.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/store.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/ttl.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/LICENSE
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/README.md
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/allocator.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/bbloom.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/btree.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/buffer.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/calloc.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/calloc_32bit.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/calloc_64bit.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/calloc_jemalloc.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/calloc_nojemalloc.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/file.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/file_default.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/file_linux.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/flags.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/histogram.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mmap.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mmap_darwin.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mmap_linux.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mmap_plan9.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mmap_unix.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mmap_wasip1.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mmap_windows.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mremap_linux.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/mremap_linux_arm64.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/rtutil.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/simd/baseline.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/simd/search.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/simd/search_amd64.s
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/simd/stub_search_amd64.go
(1 hunks)vendor/github.com/dgraph-io/ristretto/z/z.go
(1 hunks)vendor/github.com/dgryski/go-farm/.gitignore
(1 hunks)vendor/github.com/dgryski/go-farm/.travis.yml
(1 hunks)vendor/github.com/dgryski/go-farm/LICENSE
(1 hunks)vendor/github.com/dgryski/go-farm/Makefile
(1 hunks)vendor/github.com/dgryski/go-farm/README.md
(1 hunks)vendor/github.com/dgryski/go-farm/VERSION
(1 hunks)vendor/github.com/dgryski/go-farm/basics.go
(1 hunks)vendor/github.com/dgryski/go-farm/farmhashcc.go
(1 hunks)vendor/github.com/dgryski/go-farm/farmhashmk.go
(1 hunks)vendor/github.com/dgryski/go-farm/farmhashna.go
(1 hunks)vendor/github.com/dgryski/go-farm/farmhashuo.go
(1 hunks)vendor/github.com/dgryski/go-farm/farmhashxo.go
(1 hunks)vendor/github.com/dgryski/go-farm/fp_amd64.s
(1 hunks)vendor/github.com/dgryski/go-farm/fp_generic.go
(1 hunks)vendor/github.com/dgryski/go-farm/fp_stub.go
(1 hunks)vendor/github.com/dustin/go-humanize/.travis.yml
(1 hunks)vendor/github.com/dustin/go-humanize/LICENSE
(1 hunks)vendor/github.com/dustin/go-humanize/README.markdown
(1 hunks)vendor/github.com/dustin/go-humanize/big.go
(1 hunks)vendor/github.com/dustin/go-humanize/bigbytes.go
(1 hunks)vendor/github.com/dustin/go-humanize/bytes.go
(1 hunks)vendor/github.com/dustin/go-humanize/comma.go
(1 hunks)vendor/github.com/dustin/go-humanize/commaf.go
(1 hunks)vendor/github.com/dustin/go-humanize/ftoa.go
(1 hunks)vendor/github.com/dustin/go-humanize/humanize.go
(1 hunks)vendor/github.com/dustin/go-humanize/number.go
(1 hunks)vendor/github.com/dustin/go-humanize/ordinals.go
(1 hunks)vendor/github.com/dustin/go-humanize/si.go
(1 hunks)vendor/github.com/dustin/go-humanize/times.go
(1 hunks)vendor/github.com/google/uuid/CHANGELOG.md
(1 hunks)vendor/github.com/google/uuid/CONTRIBUTING.md
(1 hunks)vendor/github.com/google/uuid/CONTRIBUTORS
(1 hunks)vendor/github.com/google/uuid/LICENSE
(1 hunks)vendor/github.com/google/uuid/README.md
(1 hunks)vendor/github.com/google/uuid/dce.go
(1 hunks)vendor/github.com/google/uuid/doc.go
(1 hunks)vendor/github.com/google/uuid/hash.go
(1 hunks)vendor/github.com/google/uuid/marshal.go
(1 hunks)vendor/github.com/google/uuid/node.go
(1 hunks)vendor/github.com/google/uuid/node_js.go
(1 hunks)vendor/github.com/google/uuid/node_net.go
(1 hunks)vendor/github.com/google/uuid/null.go
(1 hunks)vendor/github.com/google/uuid/sql.go
(1 hunks)vendor/github.com/google/uuid/time.go
(1 hunks)vendor/github.com/google/uuid/util.go
(1 hunks)vendor/github.com/google/uuid/uuid.go
(1 hunks)vendor/github.com/google/uuid/version1.go
(1 hunks)vendor/github.com/google/uuid/version4.go
(1 hunks)vendor/github.com/google/uuid/version6.go
(1 hunks)vendor/github.com/google/uuid/version7.go
(1 hunks)vendor/github.com/pkg/errors/.gitignore
(1 hunks)vendor/github.com/pkg/errors/.travis.yml
(1 hunks)vendor/github.com/pkg/errors/LICENSE
(1 hunks)vendor/github.com/pkg/errors/Makefile
(1 hunks)vendor/github.com/pkg/errors/README.md
(1 hunks)vendor/github.com/pkg/errors/appveyor.yml
(1 hunks)vendor/github.com/pkg/errors/errors.go
(1 hunks)vendor/github.com/pkg/errors/go113.go
(1 hunks)vendor/github.com/pkg/errors/stack.go
(1 hunks)vendor/golang.org/x/sys/LICENSE
(1 hunks)vendor/golang.org/x/sys/PATENTS
(1 hunks)vendor/golang.org/x/sys/unix/.gitignore
(1 hunks)vendor/golang.org/x/sys/unix/README.md
(1 hunks)vendor/golang.org/x/sys/unix/affinity_linux.go
(1 hunks)vendor/golang.org/x/sys/unix/aliases.go
(1 hunks)vendor/golang.org/x/sys/unix/asm_aix_ppc64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_bsd_386.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_bsd_amd64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_bsd_arm.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_bsd_arm64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_386.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_amd64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_arm.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_arm64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_loong64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_mipsx.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_riscv64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_linux_s390x.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_solaris_amd64.s
(1 hunks)vendor/golang.org/x/sys/unix/asm_zos_s390x.s
(1 hunks)vendor/golang.org/x/sys/unix/bluetooth_linux.go
(1 hunks)vendor/golang.org/x/sys/unix/cap_freebsd.go
(1 hunks)vendor/golang.org/x/sys/unix/constants.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_aix_ppc.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_aix_ppc64.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_darwin.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_dragonfly.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_freebsd.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_linux.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_netbsd.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_openbsd.go
(1 hunks)vendor/golang.org/x/sys/unix/dev_zos.go
(1 hunks)vendor/golang.org/x/sys/unix/dirent.go
(1 hunks)vendor/golang.org/x/sys/unix/endian_big.go
(1 hunks)vendor/golang.org/x/sys/unix/endian_little.go
(1 hunks)vendor/golang.org/x/sys/unix/env_unix.go
(1 hunks)vendor/golang.org/x/sys/unix/epoll_zos.go
(1 hunks)vendor/golang.org/x/sys/unix/fcntl.go
(1 hunks)vendor/golang.org/x/sys/unix/fcntl_darwin.go
(1 hunks)vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go
(1 hunks)vendor/golang.org/x/sys/unix/fdset.go
(1 hunks)vendor/golang.org/x/sys/unix/fstatfs_zos.go
(1 hunks)vendor/golang.org/x/sys/unix/gccgo.go
(1 hunks)vendor/golang.org/x/sys/unix/gccgo_c.c
(1 hunks)vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go
(1 hunks)vendor/golang.org/x/sys/unix/ifreq_linux.go
(1 hunks)vendor/golang.org/x/sys/unix/ioctl_linux.go
(1 hunks)vendor/golang.org/x/sys/unix/ioctl_signed.go
(1 hunks)vendor/golang.org/x/sys/unix/ioctl_unsigned.go
(1 hunks)vendor/golang.org/x/sys/unix/ioctl_zos.go
(1 hunks)vendor/golang.org/x/sys/unix/mkall.sh
(1 hunks)vendor/golang.org/x/sys/unix/mkerrors.sh
(1 hunks)vendor/golang.org/x/sys/unix/mmap_nomremap.go
(1 hunks)vendor/golang.org/x/sys/unix/mremap.go
(1 hunks)vendor/golang.org/x/sys/unix/pagesize_unix.go
(1 hunks)vendor/golang.org/x/sys/unix/pledge_openbsd.go
(1 hunks)vendor/golang.org/x/sys/unix/ptrace_darwin.go
(1 hunks)vendor/golang.org/x/sys/unix/ptrace_ios.go
(1 hunks)vendor/golang.org/x/sys/unix/race.go
(1 hunks)vendor/golang.org/x/sys/unix/race0.go
(1 hunks)vendor/golang.org/x/sys/unix/readdirent_getdents.go
(1 hunks)vendor/golang.org/x/sys/unix/readdirent_getdirentries.go
(1 hunks)vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go
(1 hunks)vendor/golang.org/x/sys/unix/sockcmsg_linux.go
(1 hunks)vendor/golang.org/x/sys/unix/sockcmsg_unix.go
(1 hunks)vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go
(1 hunks)vendor/golang.org/x/sys/unix/syscall.go
(1 hunks)vendor/golang.org/x/sys/unix/syscall_aix.go
(1 hunks)vendor/golang.org/x/sys/unix/syscall_aix_ppc.go
(1 hunks)vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go
(1 hunks)vendor/golang.org/x/sys/unix/syscall_bsd.go
(1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
examples/example_ping/main.go (1)
wire/cmd.pb.go (3)
Command
(24-31)Command
(44-44)Command
(59-61)
main.go (1)
wire/cmd.pb.go (8)
Command
(24-31)Command
(44-44)Command
(59-61)Response
(77-94)Response
(107-107)Response
(122-124)Response_VStr
(208-210)Response_VStr
(224-224)
🪛 LanguageTool
vendor/github.com/google/uuid/CONTRIBUTING.md
[uncategorized] ~3-~3: The grammatical number of this noun doesn’t look right. Consider replacing it.
Context: ...bute We definitely welcome patches and contribution to this project! ### Tips Commits mus...
(AI_EN_LECTOR_REPLACEMENT_NOUN_NUMBER)
[style] ~22-~22: Consider a shorter alternative to avoid wordiness.
Context: ...documentation. ### Legal requirements In order to protect both you and ourselves, you wil...
(IN_ORDER_TO_PREMIUM)
vendor/github.com/dgryski/go-farm/README.md
[style] ~5-~5: Using many exclamation marks might seem excessive (in this case: 3 exclamation marks for a text that’s 1587 characters long)
Context: ...github.com/dgryski/go-farm/tree/master)
[
[uncategorized] ~19-~19: Possible missing comma found.
Context: ... functions mix the input bits thoroughly but are not suitable for cryptography. All...
(AI_HYDRA_LEO_MISSING_COMMA)
[typographical] ~23-~23: Consider adding a comma here.
Context: ...nkins, and others. For more information please consult https://github.com/google/farmh...
(PLEASE_COMMA)
[uncategorized] ~30-~30: This verb does not appear to agree with the subject. Consider using a different form.
Context: ....org for getting started. This project include a Makefile that allows you to test and ...
(AI_EN_LECTOR_REPLACEMENT_VERB_AGREEMENT)
vendor/github.com/dgraph-io/ristretto/README.md
[style] ~19-~19: The phrase “a variety of” may be wordy. To make your writing clearer, consider replacing it.
Context: ...ounter). * Fast Throughput - we use a variety of techniques for managing contention and ...
(A_VARIETY_OF)
[uncategorized] ~23-~23: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...st figure out your ideal Config
values and you're off and running. ## Status Ris...
(COMMA_COMPOUND_SENTENCE)
[uncategorized] ~26-~26: You might be missing the article “the” here.
Context: ...and you're off and running. ## Status Ristretto is production-ready. See [Projects usin...
(AI_EN_LECTOR_MISSING_DETERMINER_THE)
[grammar] ~106-~106: Please verify that the plural noun “increases” is in agreement with the quantifier “1”. Did you mean to use the singular form?
Context: ...st is 100 and a new item with a cost of 1 increases total cache cost to 101, 1 item will be...
(ONE_PLURAL)
[uncategorized] ~106-~106: You might be missing the article “the” here.
Context: ...d a new item with a cost of 1 increases total cache cost to 101, 1 item will be evict...
(AI_EN_LECTOR_MISSING_DETERMINER_THE)
[grammar] ~108-~108: The usual collocation for “full” is “of”, not “with”. Did you mean “full of”?
Context: ...ost is 1,000,000 (1MB) and the cache is full with 1,000 1KB items, a new item (that's acc...
(FULL_WITH_OF)
[typographical] ~116-~116: Consider wrapping this idiom with two commas if you want to put a strong emphasize on it.
Context: ...st value we've found for this is 64. If for some reason you see Get performance decreasing with...
(FOR_WHATEVER_REASON_COMMA)
[uncategorized] ~116-~116: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...s of 64. This is a fine-tuning mechanism and you probably won't have to touch this. ...
(COMMA_COMPOUND_SENTENCE)
[style] ~120-~120: The phrase “a variety of” may be wordy. To make your writing clearer, consider replacing it.
Context: ...true when you want real-time logging of a variety of stats. The reason this is a Config flag...
(A_VARIETY_OF)
[style] ~120-~120: The word “because” means “for the reason that” and thus introduces redundancy.
Context: ...stats. The reason this is a Config flag is because there's a 10% throughput performance ov...
(REASON_IS_BECAUSE)
[style] ~128-~128: The phrase “a variety of” may be wordy. To make your writing clearer, consider replacing it.
Context: ...very key. If this is nil, Ristretto has a variety of [defaults depending on the underlying i...
(A_VARIETY_OF)
[uncategorized] ~131-~131: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...st fill the uint64
at the 0
position and it will behave like any 64bit hash. **...
(COMMA_COMPOUND_SENTENCE)
[style] ~136-~136: Consider a shorter alternative to avoid wordiness.
Context: ...nal function you can pass to the Config in order to evaluate item cost at runtime, and only...
(IN_ORDER_TO_PREMIUM)
[uncategorized] ~138-~138: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...ting item cost is particularly expensive and you don't want to waste time on items t...
(COMMA_COMPOUND_SENTENCE)
[style] ~139-~139: The word ‘anyways’ is informal American English. Did you mean “anyway”?
Context: ...aste time on items that will be dropped anyways). To signal to Ristretto that you'd li...
(ANYWAYS)
[uncategorized] ~180-~180: When a number forms part of an adjectival compound, use a hyphen.
Context: ..."references to a CODASYL database for a one hour period."
<img src=...
(MISSING_HYPHEN)
[grammar] ~189-~189: Consider using either the past participle “run” or the present participle “running” here.
Context: ...oughput All throughput benchmarks were ran on an Intel Core i7-8700K (3.7GHz) with...
(BEEN_PART_AGREEMENT)
[uncategorized] ~225-~225: The preposition “into” seems more likely in this position than the preposition “in”.
Context: ...t multiple times and eventually make it in the cache. ### Is Ristretto distribute...
(AI_EN_LECTOR_REPLACEMENT_PREPOSITION_IN_INTO)
vendor/github.com/dgraph-io/ristretto/z/README.md
[duplication] ~12-~12: Possible typo: you repeated a word.
Context: ...zed for this log-entry mask: "2014/%02i/%02i %02i:%02i:%02i /info.html". Nonetheless bblo...
(ENGLISH_WORD_REPEAT_RULE)
[uncategorized] ~12-~12: A comma may be missing after the conjunctive/linking adverb ‘Nonetheless’.
Context: ...4/%02i/%02i %02i:%02i:%02i /info.html". Nonetheless bbloom should work with any other form ...
(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)
[uncategorized] ~15-~15: A punctuation mark might be missing here.
Context: ...(to optimize for smaller strings). sdbm http://www.cse.yorku.ca/~oz/hash.html~~ ...
(AI_EN_LECTOR_MISSING_PUNCTUATION)
[uncategorized] ~110-~110: Possible missing comma found.
Context: ...r than William Fitzgeralds bitset bloom filter https://github.com/willf/bloom . And it...
(AI_HYDRA_LEO_MISSING_COMMA)
[grammar] ~129-~129: The auxiliary verb ‘do’ requires the base form of the verb.
Context: ...om32) using modified sdbm, bloom32 does hashing with only 2 bit shifts, one xor and one...
(DID_BASEFORM)
[grammar] ~129-~129: Did you mean “fewer”? The noun “collisions” is countable.
Context: ...db is about as fast as fnv64a but gives less collisions with the dataset (see mask a...
(FEWER_LESS)
vendor/github.com/pkg/errors/README.md
[style] ~1-~1: Using many exclamation marks might seem excessive (in this case: 4 exclamation marks for a text that’s 2207 characters long)
Context: # errors
[
[grammar] ~3-~3: It seems that the correct verb form here is “provide”.
Context: ...b.com/pkg/errors?badge) Package errors provides simple error handling primitives. `go ...
(AGREEMENT_SENT_START_2)
[typographical] ~17-~17: After the expression ‘for example’ a comma is usually used.
Context: ...adds context to the original error. For example ```go _, err := ioutil.ReadAll(r) if er...
(COMMA_FOR_EXAMPLE)
[uncategorized] ~48-~48: Prefixes followed by proper nouns or dates are typically hyphenated.
Context: ...0 release is as follows: - 0.9. Remove pre Go 1.9 and Go 1.10 support, address outsta...
(PRE_PRO_ANTI)
vendor/github.com/dgraph-io/ristretto/CHANGELOG.md
[uncategorized] ~110-~110: Possible missing preposition found.
Context: ...e values that are less than lo (#211) - Avoid an unnecessary Load procedure in Increm...
(AI_HYDRA_LEO_MISSING_TO)
[grammar] ~144-~144: The usual collocation for “Closer” is “to”, not “from”. Did you mean simply “Closer to” or “further from”?
Context: ...#192) - Improve histogram output - Move Closer from y to z (#191) - Add histogram.Mean() meth...
(CLOSER_FROM)
vendor/golang.org/x/sys/unix/README.md
[uncategorized] ~13-~13: Use a comma before ‘so’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...ating the build system to use containers so the builds are reproducible. This is be...
(COMMA_COMPOUND_SENTENCE_2)
[uncategorized] ~45-~45: When ‘OS-specific’ is used as a modifier, it is usually spelled with a hyphen.
Context: ...s has installed on their computer. The OS specific files for the new build system are loca...
(SPECIFIC_HYPHEN)
[grammar] ~48-~48: The word “checkout” is a noun. The verb is spelled with a white space.
Context: ...e Dockerfile at ${GOOS}/Dockerfile
to checkout the new release of the source. To buil...
(NOUN_VERB_CONFUSION)
[style] ~52-~52: Consider removing “of” to be more concise
Context: .... Running mkall.sh
will then generate all of the files for all of the GOOS/GOARCH pairs ...
(ALL_OF_THE)
[style] ~52-~52: Consider removing “of” to be more concise
Context: ...will then generate all of the files for all of the GOOS/GOARCH pairs in the new build syst...
(ALL_OF_THE)
[misspelling] ~67-~67: This word is normally spelled as one.
Context: ...e docker container. ### asm files The hand-written assembly file at `asm_${GOOS}_${GOARCH}...
(EN_COMPOUNDS_HAND_WRITTEN)
[grammar] ~80-~80: The noun should probably be in the singular form.
Context: ... this file must be implemented for each GOOS/GOARCH pair. ### mksysnum Mksysnum is...
(EVERY_EACH_SINGULAR)
[misspelling] ~97-~97: This word is normally spelled as one.
Context: ...go,
syscall_${GOOS}_${GOARCH}.go` are hand-written Go files which implement system calls (...
(EN_COMPOUNDS_HAND_WRITTEN)
[misspelling] ~115-~115: This word is normally spelled as one.
Context: ...## types files For each OS, there is a hand-written Go file at ${GOOS}/types.go
(or `type...
(EN_COMPOUNDS_HAND_WRITTEN)
[style] ~168-~168: Consider removing “of” to be more concise
Context: ...{GOOS}_${GOARCH}.go` A file containing all of the system's generated error numbers, error...
(ALL_OF_THE)
[uncategorized] ~178-~178: The grammatical number of this noun doesn’t look right. Consider replacing it.
Context: ...f numeric constants for all the syscall number of the specific GOOS and GOARCH. Genera...
(AI_EN_LECTOR_REPLACEMENT_NOUN_NUMBER)
vendor/github.com/cespare/xxhash/v2/README.md
[uncategorized] ~33-~33: Possible missing comma found.
Context: ... ## Compatibility This package is in a module and the latest code is in version 2 of ...
(AI_HYDRA_LEO_MISSING_COMMA)
🪛 markdownlint-cli2 (0.17.2)
vendor/github.com/google/uuid/README.md
11-11: Heading levels should only increment by one level at a time
Expected: h2; Actual: h6
(MD001, heading-increment)
21-21: Bare URL used
null
(MD034, no-bare-urls)
vendor/golang.org/x/sys/unix/README.md
4-4: Bare URL used
null
(MD034, no-bare-urls)
69-69: Fenced code blocks should have a language specified
null
(MD040, fenced-code-language)
🪛 YAMLlint (1.35.1)
vendor/github.com/dgryski/go-farm/.travis.yml
[error] 9-9: duplication of key "branches" in mapping
(key-duplicates)
🪛 Shellcheck (0.10.0)
vendor/golang.org/x/sys/unix/mkall.sh
[warning] 53-53: Quote this to prevent word splitting.
(SC2046)
[warning] 59-59: This pattern always overrides a later one on line 59.
(SC2221)
[warning] 59-59: This pattern always overrides a later one on line 59.
(SC2221)
[warning] 59-59: This pattern never matches because of a previous pattern on line 59.
(SC2222)
[warning] 234-234: The surrounding quotes actually unquote this. Remove or escape them.
(SC2027)
[warning] 234-234: The surrounding quotes actually unquote this. Remove or escape them.
(SC2027)
vendor/golang.org/x/sys/unix/mkerrors.sh
[warning] 37-37: uname appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 39-39: includes_AIX appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 55-55: includes_Darwin appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 92-92: includes_DragonFly appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 115-115: includes_FreeBSD appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 152-152: includes_Linux appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 339-339: includes_NetBSD appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 368-368: includes_OpenBSD appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 409-409: includes_SunOS appears unused. Verify use (or export if used externally).
(SC2034)
[warning] 450-450: Assigning an array to a string! Assign as array, or use * instead of @ to concatenate.
(SC2124)
🪛 golangci-lint (1.64.8)
main.go
27-27: field mu
is unused
(unused)
🔇 Additional comments (414)
vendor/golang.org/x/sys/unix/constants.go (1)
1-14
: LGTM: Constants for file permission checking are correctly defined.These constants (R_OK, W_OK, X_OK) are standard POSIX values used for checking file permissions via access functions. The values are correctly defined according to POSIX standards, and the file includes proper build constraints for all supported Unix-like operating systems. The inclusion of both the newer
//go:build
directive and the older+build
comment format ensures compatibility with different Go versions.vendor/golang.org/x/sys/unix/dev_zos.go (5)
5-6
: Build tags look good.The code correctly uses both the newer
//go:build
directive and the older// +build
comment style for backward compatibility, ensuring proper compilation constraints for z/OS on s390x architecture.
8-12
: Documentation is clear and helpful.The comment effectively explains the purpose of the file and correctly references the source of the implementation details (
<sys/stat.h>
macros), providing valuable context for developers.
15-18
: Implementation of Major function looks correct.The function correctly extracts the major component from a z/OS device number by using bit shifting (right by 16 bits) and masking operations.
20-23
: Implementation of Minor function looks correct.The function correctly extracts the minor component from a z/OS device number by applying the appropriate bit mask.
25-29
: Implementation of Mkdev function looks correct.The function properly combines major and minor components into a single device number using bit shifting and OR operations, providing the inverse operation to Major and Minor functions.
vendor/golang.org/x/sys/unix/asm_aix_ppc64.s (3)
1-19
: Implementation follows Go assembly best practices.This assembly file properly implements system call entry points for AIX on the PPC64 architecture. The use of NOSPLIT is appropriate for system calls as it prevents stack splitting during execution, which is essential for maintaining the correct stack layout when interacting with the operating system. The file correctly delegates the actual implementation to the Go runtime package as indicated in the comments.
14-15
: System call implementation matches established pattern.The
syscall6
function is correctly implemented as a simple jump to the corresponding function in the runtime package. The function signature with$0-88
indicates 0 bytes of local variables and 88 bytes for arguments and return values, which is consistent with a system call taking 6 parameters.
17-18
: Raw system call implementation matches established pattern.The
rawSyscall6
function follows the same pattern assyscall6
, providing an entry point for raw system calls (those that don't retry on EINTR). This implementation is consistent with similar functions in other architecture-specific assembly files in the x/sys/unix package.vendor/golang.org/x/sys/unix/dev_aix_ppc64.go (1)
1-12
: LGTM: Build constraints and package declaration look good.The build constraints correctly specify this file is only for AIX on PPC64 architecture, and the package declaration is appropriate.
vendor/golang.org/x/sys/unix/dev_aix_ppc.go (2)
1-12
: LGTM: Build constraints and package declaration look good.The build constraints correctly specify this file is only for AIX on PPC architecture, and the package declaration is appropriate.
1-28
: Verify the different device number formats between PPC and PPC64I notice the implementation of device number handling differs significantly between PPC and PPC64:
- PPC: Major is the high 16 bits, minor is the low 16 bits
- PPC64: Major is bits 32-61, minor is bits 0-31, with a special flag DEVNO64 (0x8000000000000000)
Please verify that these different implementations are intentional and correctly match AIX's device number format on the respective architectures.
vendor/github.com/dgryski/go-farm/VERSION (1)
1-2
: Review Version File Content.
The file is meant to specify the version as2.0.1
, but it appears to contain an extra line with a lone2
. Please verify if the second line is intentional or if it should be removed to avoid confusion in dependency management.vendor/github.com/cespare/xxhash/v2/.travis.yml (1)
1-9
: CI Configuration Looks Good.
The Travis CI configuration is well defined with the Go versions "1.x" and "master", along with two environments (one default and one with the-tags purego
flag). Confirm that both environments are required for your testing strategy.vendor/github.com/google/uuid/LICENSE (1)
1-28
: Google LICENSE File is Standard.
The license text matches the expected Google Inc. license, including the necessary permissions, disclaimers, and conditions. No changes are needed here; just ensure that future modifications (if any) are tracked in version control.vendor/github.com/cespare/xxhash/v2/LICENSE.txt (1)
1-23
: MIT License File is Correct.
The MIT License text is complete and accurate, including attribution to Caleb Spare. This file properly grants the permissions and includes all necessary conditions.vendor/github.com/dustin/go-humanize/LICENSE (1)
1-22
: LICENSE file for go-humanize added correctly
The new LICENSE file properly incorporates the MIT license text with clear attribution. It meets open source and legal compliance requirements.vendor/github.com/pkg/errors/LICENSE (1)
1-24
: LICENSE for pkg/errors added correctly
The LICENSE file for the pkg/errors package has been added with an appropriate copyright notice and standard redistribution terms.vendor/github.com/pkg/errors/.gitignore (1)
1-25
: .gitignore for pkg/errors is comprehensive
This .gitignore file correctly lists common build artifacts, object files, and temporary files to be ignored by Git, ensuring the repository remains clean.vendor/golang.org/x/sys/LICENSE (1)
1-28
: LICENSE for golang.org/x/sys added correctly
The LICENSE file accurately reflects the copyright notice and redistribution conditions for this package, adhering to the original terms provided by The Go Authors.vendor/github.com/dgryski/go-farm/fp_stub.go (1)
1-10
: Auto-generated fingerprint stub file verified
This auto-generated file provides the function stubs for Fingerprint64 and Fingerprint32 with proper build constraints for the amd64 architecture. As it is generated code, it should not be modified manually.vendor/github.com/pkg/errors/appveyor.yml (1)
1-32
: Configuration looks goodThis AppVeyor CI configuration follows the standard patterns for Go projects, correctly setting up the environment, build, and test process.
vendor/github.com/dgryski/go-farm/fp_generic.go (1)
1-14
: Implementation looks goodThe fingerprint functions are well-defined with appropriate build constraints for non-amd64 architectures. The functions provide a clean interface for generating both 32-bit and 64-bit fingerprints from byte slices.
vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go (1)
8-16
: Alignment implementation is well-designedThe function correctly handles the alignment of socket control message headers, including special handling for older 64-bit DragonFly BSD systems. The bitwise calculation for alignment is efficient and follows standard practice.
vendor/github.com/dgraph-io/ristretto/z/LICENSE (1)
1-64
: License file is properly documentedThe LICENSE file correctly attributes the original components (bbloom.go and rtutil.go) under MIT License with their respective copyright holders, while also specifying the Apache License 2.0 for modifications by Dgraph Labs.
vendor/golang.org/x/sys/PATENTS (1)
1-22
: LGTM: Standard Google patent license for Go projectsThe patent license is correctly included and properly formatted. This is a standard legal document included with Go projects from the golang.org/x namespace.
vendor/github.com/dgraph-io/ristretto/LICENSE (1)
1-176
: LGTM: Standard Apache License 2.0The license file is correctly included and properly formatted. This is the standard Apache License 2.0 that's required for using the Ristretto caching library.
vendor/github.com/cespare/xxhash/v2/xxhash_amd64.go (1)
1-13
: LGTM: Properly configured hash function declarationsThe build tags are correctly configured to ensure this implementation is only used in appropriate environments. Both functions use the
//go:noescape
compiler directive which is appropriate for optimized hash functions as it prevents escape analysis overhead.vendor/github.com/dgraph-io/ristretto/CHANGELOG.md (1)
1-187
: LGTM: Well-formatted changelogThe changelog follows the "Keep a Changelog" format and Semantic Versioning principles. It provides good documentation of the library's evolution with categorized changes and links to relevant PRs.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~110-~110: Possible missing preposition found.
Context: ...e values that are less than lo (#211) - Avoid an unnecessary Load procedure in Increm...(AI_HYDRA_LEO_MISSING_TO)
[grammar] ~144-~144: The usual collocation for “Closer” is “to”, not “from”. Did you mean simply “Closer to” or “further from”?
Context: ...#192) - Improve histogram output - Move Closer from y to z (#191) - Add histogram.Mean() meth...(CLOSER_FROM)
vendor/github.com/dgraph-io/ristretto/.golangci.yml (1)
1-29
: Standard linting configuration looks good.This file sets up a typical configuration for Go linting using golangci-lint, with appropriate excludes for
math/rand
usage and a reasonable line length limit of 120 characters. The selective enabling of linters provides a good balance between code quality and practicality.vendor/golang.org/x/sys/unix/dev_openbsd.go (3)
10-13
: Implementation matches OpenBSD device number format.The bit manipulation for extracting the major device number correctly handles the OpenBSD device number encoding.
15-20
: Correctly extracts the minor device number.The implementation properly combines bits from different positions in the device number to form the complete minor number according to OpenBSD's encoding standard.
22-29
: Device number construction looks good.The
Mkdev
function correctly assembles the device number by placing the major and minor components in their appropriate bit positions according to OpenBSD's convention.vendor/github.com/dgryski/go-farm/basics.go (4)
5-8
: Well-chosen prime constants for hashing.These prime number constants are appropriately selected for hashing functions, providing good distribution properties.
10-12
: Standard Murmur3 constants.These constants match the ones used in the Murmur3 hashing algorithm, which is a good choice for fast, non-cryptographic hashing.
14-22
: Proper implementation of the fmix function.This mixing function follows the standard pattern for finalizing hash values in Murmur3, with appropriate bit manipulation operations to achieve good avalanche effects.
24-32
: Correct implementation of the mur helper function.The function properly implements the mixing step from Murmur3, using the standard constants and bit rotation operations.
vendor/github.com/dgryski/go-farm/README.md (1)
5-5
: Acknowledge possible false-positive style warning.The multiple exclamation marks in this line come from standard Markdown syntax for image badges (e.g.,

). This is likely a harmless false positive from the style checker.vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s (3)
1-3
: Validate build tags usage.The build tags are properly excluding App Engine, requiring gc, and skipping pure Go implementations. This seems intentional to ensure the assembly-based optimization is included only when relevant. No changes required.
57-59
: Check for short slice handling.The jump to
noBlocks
is guarded byCMPQ DX, $32
followed byJLT noBlocks
. This cleanly handles cases where the input slice is shorter than 32 bytes, preventing out-of-bounds reads in the block loop. Looks correct.
194-195
: Confirm the guaranteed minimum block condition.The comment states this function is “always called with at least one block of data to process.” Please ensure all callers adhere to that contract. If there's any call site that might pass fewer than 32 bytes, it could lead to undefined behavior.
Would you like a script to search for potential caller sites that pass short slices to
writeBlocks
?vendor/golang.org/x/sys/unix/dev_netbsd.go (1)
11-29
:✅ Verification successful
Check correctness against official NetBSD references.
The bit masks and shifts look correct for extracting and composing device major/minor numbers on NetBSD. Ensure that these match the latest NetBSD definitions. Otherwise, this LGTM.
You can confirm correctness by checking the source code for
<sys/types.h>
in upstream NetBSD or searching the web for the official documentation on NetBSD device encodings.
🌐 Web query:
NetBSD device encoding major minor
💡 Result:
In NetBSD, device encoding using major and minor numbers follows the Unix tradition with specific implementation details:
Major Number Assignment
- Major numbers are statically assigned in configuration files:
- Architecture-independent devices:
/usr/src/sys/conf/majors
- Architecture-specific (e.g., i386):
/usr/src/sys/arch/i386/conf/majors.i386
- Example entry:
device-major skeleton char 140 skeleton
assigns major 140 to a pseudo-device[1].System Representation
Devices are represented in two key contexts:
Kernel/driver level:
- Major number identifies the driver (via
cdevsw
/bdevsw
tables)- Minor number handled internally by driver (often via
softc
struct)[1][2]Filesystem/tools:
- Mtree format:
netbsd,major,minor
Example:device=netbsd,140,0
[4][7]- Tar archives: Stored in
SCHILY.devmajor
/SCHILY.devminor
extended attributes[8]Minor Number Usage
- Managed per driver (e.g., 0 for single-instance devices[2])
- Common approaches:
- Direct use: Single minor for simple devices
- Softc allocation: One
softc
struct per minor[1]struct rperm_softc { // Example from pseudo-device char *buf; int buf_len; } sc[2];Device Node Creation
Using
mknod
with explicit major/minor:mknod /dev/rperm c 420 0 # major=420, minor=0[2]
Key implementation details:
- Major numbers ≥144 are dynamically assigned for pseudo-devices[1]
- Historical 16-bit minor limit (now extended to 32-bit via
dev_t
changes)- Maintains compatibility with POSIX device encoding standards[7][8]
This system allows precise device management while maintaining cross-tool compatibility through standardized encoding formats.
Citations:
- 1: https://www.netbsd.org/docs/kernel/pseudo/
- 2: https://saurvs.github.io/post/writing-netbsd-kern-mod/
- 3: https://wiki.netbsd.org/tutorials/bus_space_tutorial/
- 4: https://man.netbsd.org/mtree.5
- 5: https://www.netbsd.org/docs/guide/en/chap-cgd.html
- 6: https://en.wikipedia.org/wiki/NetBSD
- 7: https://man.netbsd.org/mtree.8
- 8: https://man.netbsd.org/tar.5
- 9: http://man.netbsd.org/NetBSD-2.0/pstat.8
NetBSD Device Encoding Verified
The code correctly extracts the 12‐bit major number (from bits 8–19) and combines the lower 8 bits with the upper 12 bits to form a 20‐bit minor number, which matches the official NetBSD device encoding scheme described in the latest documentation. No changes are needed.vendor/golang.org/x/sys/unix/dev_dragonfly.go (1)
1-30
: LGTM! The implementation correctly handles DragonFlyBSD device numbers.The functions correctly implement device number encoding for DragonFlyBSD:
Major
extracts the major component by shifting right by 8 bits and maskingMinor
retrieves the minor component with the appropriate bit maskingMkdev
properly combines major and minor components as described in the commentsThe comments also provide good context about the DragonFlyBSD-specific implementation details.
vendor/github.com/dgraph-io/ristretto/z/mmap_plan9.go (1)
24-44
: Implementation correctly provides Plan 9 placeholders returning appropriate errors.These placeholder functions for memory mapping operations on Plan 9 follow the Go pattern for unsupported OS features. All functions return
syscall.EPLAN9
error as expected, which is the correct approach for this platform.Note that these unexported functions (starting with lowercase) are likely intended to be used internally by other exported functions in the package that handle cross-platform compatibility.
vendor/golang.org/x/sys/unix/dev_linux.go (2)
20-32
: LGTM! Functions correctly extract Linux device number components.The implementation correctly follows the Linux device number encoding described in the comments. The bitwise operations properly extract the major and minor components according to the glibc encoding format.
34-42
: LGTM! Function correctly combines Linux device number components.The
Mkdev
implementation correctly combines the major and minor components using the appropriate bitwise operations to create a Linux device number that follows the glibc encoding format.vendor/github.com/dustin/go-humanize/bytes.go (2)
11-62
: LGTM! Constants and mapping table for byte size conversions are well-defined.The file correctly defines constants for both IEC (binary) and SI (decimal) byte sizes. The
bytesSizeTable
mapping is comprehensive, including entries for both full unit names and their abbreviated forms, which provides good flexibility for parsing.
83-101
: LGTM! Human-readable conversion functions are well-implemented.The
Bytes
andIBytes
functions correctly implement the conversion of byte sizes into human-readable formats using SI and IEC units respectively. The implementations are concise and leverage the helper functionhumanateBytes
for the core formatting logic.vendor/github.com/dgraph-io/ristretto/z/mmap_windows.go (1)
28-82
: LGTM: Memory mapping implementation is correctThe memory mapping implementation for Windows correctly:
- Sets appropriate protection and access flags
- Truncates the file if necessary
- Properly handles resource cleanup
- Correctly handles size calculations
- Safely creates Go slice from mapped memory
vendor/golang.org/x/sys/unix/mkerrors.sh (1)
14-17
: LGTM: Environment variable validationThe script correctly checks for required GOARCH and GOOS environment variables before proceeding.
vendor/github.com/dustin/go-humanize/times.go (1)
1-117
: Looks good—clean and well-documented implementation.The relative time formatting logic is straightforward and thoughtfully laid out. No further changes needed here.
vendor/github.com/dgraph-io/ristretto/ring.go (8)
1-15
: Licensing and header look good.
No issues found.
17-21
: Package and imports are appropriate.
The use ofsync
seems fitting for handling concurrency aspects.
29-34
: Struct definition is clear.
Maintaining the capacity in anint
is acceptable for most practical use cases.
36-42
: Factory function is straightforward.
Initialization logic is concise and aligns with the struct’s expectations.
44-57
: Push method logic is consistent.
Appending items and draining upon capacity threshold is clear. The reset pathway (make([]uint64, 0, s.capa)
) is a valid way to refresh the buffer.
59-66
: Struct for ring buffer is minimal and effective.
Sync pool usage is appropriate for reducing allocations.
68-82
: Initialization of ringBuffer is correct.
Lossy nature of stripes insync.Pool
due to GC is acknowledged and well documented.
84-91
: Push method concurrency approach.
Retrieving a stripe from the pool, pushing, then returning it ensures minimal contention. Confirm that external usage consistently pairs Get/Put calls to avoid resource leakage.vendor/github.com/dgraph-io/ristretto/z/calloc_nojemalloc.go (6)
1-7
: License and build constraints.
The build tags clearly segregate jemalloc vs. non-jemalloc builds.
8-16
: Package, imports, and commentary.
Documentation is sufficient to convey the intent of these no-jemalloc functions.
17-20
: Calloc function.
This straightforward allocation aligns with standard Go memory usage.
28-29
: Free function is no-op.
This is consistent with Go’s runtime garbage collection approach.
31-34
: Leaks / StatsPrint.
Simple pass-through messaging is clear about the usage of native Go memory.
36-38
: ReadMemStats is intentionally unimplemented.
No issues observed since the Go runtime handles all memory stats.vendor/golang.org/x/sys/unix/bluetooth_linux.go (3)
9-19
: Bluetooth protocol constants.
Values appear to match standard Linux definitions.
21-27
: HCI channel constants.
No discrepancies found with known kernel constants.
29-36
: Socket option level constants.
Valid hex values correspond to documented Bluetooth socket levels in Linux.vendor/github.com/dgraph-io/ristretto/ttl.go (10)
1-15
: License and disclaimers.
No issues found.
17-22
: Package and imports.
Usage ofsync
andtime
is typical for concurrency and scheduling.
29-37
: storageBucket / cleanupBucket calculations.
Logic to offset cleanup for an additional interval ensures elements are not prematurely removed. Implementation is clear.
39-41
: bucket type
A map from key → conflict is straightforward.
42-46
: expirationMap struct
Use of read-write lock is appropriate for concurrent access to buckets.
48-52
: newExpirationMap initialization
Instantiating the buckets map ensures subsequent methods can reliably store data.
54-74
: add method
Items that don’t expire are skipped, preserving memory. Bucket creation logic is safe and concurrency is well-managed with locks.
76-97
: update method
Removing the old bucket reference before inserting into the new prevents stale references. Lock usage is consistent.
99-112
: del method
Skipping if the expiration is zero or if no bucket is found avoids unnecessary map operations.
114-149
: cleanup method
Periodic cleanup approach is robust. Validating expiration via store ensures no premature eviction, and the onEvict callback is invoked as needed.vendor/github.com/google/uuid/time.go (3)
33-40
: Validate negative or pre-epoch times.When computing
sec
andnsec
fromt - g1582ns100
, ensure that negative values oft
are handled as expected.
51-67
: Clock sequence incrementation logic is sound.This correctly increments the clock sequence and sets the higher variant bit if the new time is not strictly greater than
lasttime
. The approach matches the recommended practice for version-based UUID generation.
110-128
: Forward compatibility for Version 6 and 7.The switch statement properly accounts for multiple UUID versions, extracting the time field differently. This design ensures easier extension of future versions without breaking older logic.
vendor/github.com/google/uuid/null.go (3)
34-49
: Check for consistent error handling in Scan.The logic properly sets
(nu.UUID, nu.Valid) = (Nil, false)
ifvalue
isnil
. For non-nil values,nu.UUID.Scan(value)
is delegated. Confirm that any errors fromScan
are appropriately tested downstream.
60-67
: Binary marshaling aligns with typical Null-value semantics.Returning an empty slice for invalid UUIDs is consistent with the
MarshalBinary
contract for null-like data. No issues spotted.
109-118
: JSON handling of null UUIDs is correct.The check
bytes.Equal(data, jsonNull)
ensures valid detection of null. The fallback to parsing the UUID withjson.Unmarshal
for non-null data is standard.vendor/github.com/google/uuid/dce.go (4)
23-40
: Check cross-platform UID/GID usage.
NewDCESecurity
and its domain-based customization are aligned with Version 2 (DCE Security). Ensureos.Getuid()
andos.Getgid()
usage is correct on all target platforms if compiled outside POSIX systems.
33-37
: Version field setting is correct.Setting
uuid[6] = (uuid[6] & 0x0f) | 0x20
properly encodes the version 2 bits in the UUID.
50-56
: Group domain usage.
NewDCEGroup
parallelsNewDCEPerson
, substitutingos.Getgid()
. The logic is straightforward and consistent.
70-80
: Domain string method is comprehensive.Covers all known domain constants and provides a fallback format for unknown domains, ensuring robust string representation.
vendor/golang.org/x/sys/unix/cap_freebsd.go (5)
17-29
: Constants and lookup table look consistent.
The capability version and bounds defined here appear aligned with FreeBSD’s capability approach, and thebit2idx
array seems correctly designed for bit-to-index mapping. No immediate issues from a correctness or performance standpoint.
31-53
: Index and version extraction helpers are well-structured.
capidxbit()
,rightToIndex()
, and related version helpers cleanly encapsulate the bit manipulations, reducing the likelihood of errors. The explicit error messages (e.g., “out of range”) help with debug workflows.
125-157
: Logical check for membership is correct.
CapRightsIsSet
correctly handles partial mismatches. If any required right is absent, it returns a Boolean false immediately. This is well-structured and should behave reliably in production.
163-175
: Initialization logic is clean.
CapRightsInit
properly sets up defaults before applying specified rights. No issues detected with memory usage or correctness; the appended version bits and structure layout look in line with the rest of the file.
177-196
: CapRightsLimit and CapRightsGet usage is straightforward.
These routines cleanly wrap the underlying syscalls, preserving errors and providing an idiomatic Go interface. Their minimal logic appears correct and consistent with the rest of the library.vendor/github.com/dustin/go-humanize/bigbytes.go (4)
10-62
: IEC and SI expansions for big.Int look correct.
The definitions ofbigIECExp
,bigSIExp
, and the associated big byte constants are consistent and logically grouped. This should handle large-scale conversions reliably.
64-108
: Extensive suffix map is handy for parsing and canonicalization.
ThebigBytesSizeTable
covers both IEC/IEC-based suffixes and short forms. Converting suffixes to lowercase ensures uniform handling of user input. This approach looks robust.
110-146
: Human-readable size formatting is straightforward.
ThehumanateBigBytes
helper and public wrappers (BigBytes
,BigIBytes
) appear correct. The threshold-based approach for numeric formatting (e.g., using one decimal if < 10) is a nice UX detail.
148-190
: Parsing byte strings is comprehensive.
ParseBigBytes
handles various suffixes, optional commas, and decimal inputs. Error reporting when encountering an unknown suffix is clear. This meets typical needs for human-readable byte input.vendor/golang.org/x/sys/unix/ifreq_linux.go (4)
28-41
: Interface name validation is correct.
NewIfreq
enforcesIFNAMSIZ - 1
, leaving room for the trailing null character. ReturningEINVAL
for overly long names is aligned with typical kernel constraints.
50-88
: IPv4 address getters/setters are well-defined.
The checks for the correct address family and address length help prevent invalid assignments. Clearing residual data inSetInet4Addr()
viaifr.clear()
is a good safety measure.
90-118
: Flag and metric getters/setters are concise.
Uint16
,SetUint16
,Uint32
, andSetUint32
reliably read and write kernel-compatible numeric fields. The zeroing of union data before setting values prevents leftover bits from prior usage.
123-143
: Pointer-based ifreqData approach looks appropriate.
withData
offers a safer path for ioctls needing pointer data without mixing pointer references in the raw ifreq byte array. This maintains correct alignment and preserves type safety within the Go domain.vendor/github.com/dgraph-io/ristretto/sketch.go (2)
65-70
: Increment logic appears correct.The loop and hashing operations look appropriate. Each row is incremented by XOR-ing with its seed, ensuring distribution of counters. No concerns here.
109-120
:✅ Verification successful
Confirm handling of overflow wrap-around logic.
The
if v < 15
check prevents overflow from saturating the 4-bit counter but never decreases it, potentially skewing usage data over time if calls toReset()
are infrequent. Verify that this behavior is intended for your use case.
🏁 Script executed:
#!/bin/bash # Searching for references to increment usage to confirm the presence of frequent resets rg -A 5 'Increment'Length of output: 2957
Confirmation: The 4-bit Saturating Counter Behavior Is Intentional
The implementation in
cmRow.increment
correctly prevents counter wrap-around by saturating the value at 15. As observed in the LFU policy (invendor/github.com/dgraph-io/ristretto/policy.go
), a reset is triggered when the increment counter reaches a threshold (p.resetAt
), ensuring that usage data is periodically cleared even if some counters temporarily saturate. Please ensure that the reset frequency aligns with your workload requirements to avoid any potential skew in frequency estimates.vendor/github.com/dustin/go-humanize/humanize.go (1)
1-8
: Well-documented package introductionThe package documentation clearly describes the purpose of the humanize package and gives good examples of its functionality. The formatting and structure follow Go's standard documentation practices.
vendor/github.com/pkg/errors/.travis.yml (1)
1-10
: Standard Travis CI configurationThe configuration correctly specifies multiple Go versions to test against (1.11.x through 1.13.x plus the development tip) and sets up the appropriate import path and build command.
vendor/github.com/google/uuid/doc.go (1)
1-12
: Clear and concise package documentationThe documentation properly explains the purpose of the uuid package, references the relevant standards (RFC 4122 and DCE 1.1), and provides key information about UUIDs. The formatting follows Go's documentation conventions.
vendor/golang.org/x/sys/unix/endian_little.go (2)
5-6
: Consider updating the build tags syntaxWhile the code uses both the newer
//go:build
directive and the older// +build
style for compatibility, note that the older style will eventually be phased out. This is correct for now as it maintains backward compatibility with older Go versions.
8-10
: Appropriate endianness constantThe constant correctly defines
isBigEndian
asfalse
for little-endian architectures, which matches the file name and build constraints.vendor/golang.org/x/sys/unix/pagesize_unix.go (2)
5-6
: Build constraints correctly target Unix-like systemsThe file properly uses both new and old build tag syntax for compatibility across Go versions, and correctly targets Unix-like systems where this implementation applies.
14-16
: Clean wrapper implementationThe
Getpagesize()
function provides a clean wrapper around the syscall implementation, maintaining API consistency within the unix package.vendor/golang.org/x/sys/unix/endian_big.go (2)
5-6
: Well-defined build constraints for big-endian architecturesThe build constraints correctly identify and target big-endian architectures, ensuring the
isBigEndian
constant is only included in builds for those specific platforms.
10-10
: Appropriate constant definition for endiannessThis constant properly defines the endianness for target architectures, which is essential for byte order operations in system-level programming.
vendor/github.com/dustin/go-humanize/ordinals.go (2)
5-8
: Well-documented exported functionThe documentation clearly explains the function's purpose with a helpful example, following Go's best practices for public API documentation.
8-25
: Comprehensive handling of ordinal suffixesThe function correctly handles all edge cases for English ordinal numbers, including the special cases for 11th, 12th, and 13th where the usual rules for numbers ending in 1, 2, and 3 don't apply.
vendor/golang.org/x/sys/unix/mmap_nomremap.go (2)
5-6
: Proper OS targeting for memory mapping implementationThe build constraints correctly target Unix-like operating systems that don't support the mremap system call, ensuring platform-specific memory mapping behavior.
10-14
: Correct initialization of memory mapperThe mapper variable is properly initialized with an active mapping tracker and the appropriate memory mapping functions, providing the foundation for memory-mapped operations on these platforms.
vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go (2)
5-6
: Precise architecture targeting for 32-bit Linux systemsThe build constraints correctly identify 32-bit Linux architectures where special handling for fcntl operations is required.
10-14
: Platform-specific syscall correction for file lockingThis initialization properly sets the correct syscall (SYS_FCNTL64) for file control operations on 32-bit Linux systems, ensuring proper file locking functionality with Go's Flock_t type.
vendor/github.com/dgryski/go-farm/LICENSE (1)
1-21
: License file looks good.This is a standard MIT license file for the go-farm package, properly attributing the copyright to Damian Gryski and Nicola Asuni. The MIT license is permissive and commonly used in open-source projects, allowing for both commercial and non-commercial use.
vendor/github.com/google/uuid/node_js.go (2)
5-6
: Build tag syntax is correct.The build tag
+build js
ensures this file is only compiled when targeting JavaScript (likely using GopherJS or WebAssembly).
9-12
: Implementation provides JavaScript optimization.This implementation correctly provides a no-op version of
getHardwareInterface
for JavaScript builds, which helps reduce the compiled JS size by removing the "net" dependency. The function signature matches what would be expected in the non-JS version, ensuring compatibility.examples/example_ping/main.go (4)
19-21
: SET command implementation looks good.The code correctly fires a SET command to store "bar" under the key "foo". The response is properly printed to stdout.
22-24
: GET command implementation looks good.The code correctly retrieves the previously set value for key "foo". The response is properly printed to stdout.
25-27
: Testing non-existent key is good practice.Testing the GET command with a non-existent key "foo1" is a good practice to verify how the client handles keys that haven't been set.
28-28
: Good resource management with client.Close().Adding the
client.Close()
call ensures proper cleanup of resources when the client is no longer needed.vendor/github.com/dgryski/go-farm/.gitignore (1)
1-24
: Standard Go .gitignore file.This is a standard .gitignore file for Go projects, correctly excluding common build artifacts, object files, and temporary files. Appropriately vendored as part of the dependency.
vendor/github.com/dgraph-io/ristretto/z/calloc_64bit.go (1)
1-6
: Appropriate Build Constraints and File Metadata
The copyright notice and build tag comments are formatted correctly and provide the necessary build constraint details for the supported architectures.vendor/github.com/dgraph-io/ristretto/z/calloc_32bit.go (1)
9-14
: Concise Constants for 32-bit Architectures
The constantsMaxArrayLen
andMaxBufferSize
are clearly defined for 32-bit architectures using bit shifts, mirroring the approach in the 64-bit file.vendor/github.com/google/uuid/README.md (1)
1-10
: Comprehensive README for the UUID Package
The README provides a clear overview of the package functionality and its basis on RFC 4122 and DCE 1.1 standards. The installation instructions and reference to online documentation are especially helpful.vendor/golang.org/x/sys/unix/readdirent_getdirentries.go (1)
17-19
: Note the TODO item about potential optimizationThe code creates a new uint64 for the base pointer with each call, and the TODO comment suggests a potential optimization by using a single global base pointer. Since this is vendored code, you shouldn't modify it directly, but it's worth noting if this function gets called frequently in your application.
vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go (1)
12-21
: Implementation looks correctThis code properly interfaces with the system's gettimeofday function for Linux AMD64 when using the gccgo compiler. The error handling follows the standard pattern of converting negative return values to syscall.Errno.
vendor/golang.org/x/sys/unix/asm_solaris_amd64.s (1)
14-18
: Assembly stubs look correctThese assembly stubs correctly forward system calls to the implementations in the runtime package using NOSPLIT for efficiency. This is the standard pattern for Solaris system calls on AMD64.
vendor/github.com/google/uuid/version6.go (2)
49-51
: Consider verifying the behavior of setNodeInterface with empty stringThis code calls
setNodeInterface("")
when nodeID is zero. Calling this function with an empty string parameter typically triggers a search across all system interfaces. Verify if this is the intended behavior for UUID generation in your application.
42-53
: Overall implementation is correctThe implementation correctly constructs Version 6 UUIDs with proper time encoding, version/variant bits, and node ID. The mutex usage ensures thread safety when accessing shared state.
vendor/golang.org/x/sys/unix/readdirent_getdents.go (1)
10-13
: Implementation looks good.The ReadDirent function is a clean wrapper around Getdents with proper documentation. The function signature accepts a file descriptor and buffer, returning the number of entries read and any error encountered.
vendor/github.com/google/uuid/version1.go (1)
19-44
: Well-implemented UUID version 1 generator.The NewUUID function correctly implements a Version 1 UUID generator according to the specification, with:
- Proper time-based generation
- Correct version bit setting (timeHi |= 0x1000)
- Thread-safe node ID handling with mutex
- Appropriate error handling
- Efficient binary encoding
vendor/github.com/dgraph-io/ristretto/z/mremap_linux.go (1)
31-57
: Appropriate implementation of Linux mremap syscall.The function correctly wraps the Linux-specific mremap system call, which allows remapping memory pages. The implementation:
- Uses the correct syscall parameters
- Properly handles error conditions
- Correctly updates the slice header to reflect the new memory mapping
Note that this code necessarily uses unsafe operations to manipulate memory directly, which is appropriate for this low-level system function but requires careful handling.
vendor/golang.org/x/sys/unix/ptrace_ios.go (1)
12-18
: Appropriate stub implementation for iOS platform.These stub implementations of ptrace functions correctly return ENOTSUP, properly indicating that these operations are not supported on iOS. This is the expected pattern for maintaining API compatibility across platforms while respecting platform-specific limitations.
vendor/github.com/google/uuid/util.go (3)
11-16
: Well-implemented random data generation.The
randomBits
function correctly usesio.ReadFull
to ensure the byte slice is completely filled with random data. The panic approach is appropriate here since random generation failures typically indicate critical system-level issues that cannot be recovered from gracefully.
18-36
: Efficient hex conversion lookup table.The
xvalues
array provides an efficient O(1) lookup mechanism for converting hex characters to their byte values. The use of 255 as an invalid marker is a good choice since it's outside the valid hex value range (0-15).
38-43
: Clean hex-to-byte conversion implementation.The
xtob
function effectively combines two hex characters into a single byte using bit manipulation, while also validating both characters are valid hex digits. This is an optimal implementation for this common UUID parsing operation.vendor/golang.org/x/sys/unix/ptrace_darwin.go (2)
5-6
: Properly defined build constraints.The file correctly uses both modern (
//go:build
) and legacy (// +build
) build constraint syntaxes for maximum compatibility across different Go versions.
12-18
: Well-defined ptrace wrapper functions.Both
ptrace
andptracePtr
functions provide a clean interface to the Darwin-specific ptrace system call implementation, with appropriate parameter types for different use cases.vendor/github.com/cespare/xxhash/v2/xxhash_safe.go (1)
8-15
: Safe but potentially inefficient string handling.Both functions implement safety by converting strings to byte slices, which is necessary for App Engine compatibility but introduces allocation overhead. This is an appropriate trade-off given the constraints.
vendor/github.com/dgraph-io/ristretto/z/mremap_linux_arm64.go (1)
26-52
: Well-documented ARM64-specific mremap implementation.The implementation correctly handles the Linux-specific mremap system call for ARM64 architecture with proper documentation of the architectural differences. The unsafe operations are necessary and properly implemented for this low-level memory manipulation.
A couple of notes:
- The error handling is appropriate, returning the errno directly.
- The comment about ARM64's inconsistent return value is helpful documentation.
vendor/github.com/dustin/go-humanize/commaf.go (2)
1-3
: Build constraint looks good.Using both modern
//go:build
and legacy+build
formats ensures compatibility across all Go versions.
12-14
: Good function documentation.The comments clearly explain the purpose of the function and its behavior.
vendor/github.com/dgraph-io/ristretto/z/file_default.go (2)
1-2
: Build constraint correctly excludes Linux platforms.Using both modern
//go:build
and legacy+build
formats ensures compatibility across all Go versions.
24-27
: Clear documentation explaining platform-specific behavior.The comment clearly explains the different implementation strategies for Linux vs. other systems.
vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s (3)
5-8
: Build constraints are properly defined for PPC64/PPC64LE Linux systems.The constraints correctly target Linux on PPC64/PPC64LE architectures using the Go compiler.
19-32
: Implementation of SyscallNoError looks correct.The function properly:
- Notifies the runtime of syscall entry/exit
- Sets up registers with arguments
- Executes the syscall
- Returns results to the caller
This follows the established pattern for syscall implementations on other architectures.
34-45
: Implementation of RawSyscallNoError looks correct.This implementation is similar to SyscallNoError but correctly omits the runtime notifications, which is appropriate for raw syscalls.
vendor/golang.org/x/sys/unix/dev_darwin.go (3)
5-7
: Good documentation explaining the purpose.The comment clearly explains the purpose of these functions within the Darwin context.
10-13
: Implementation of Major function is correct.The bit manipulation correctly extracts the major number according to Darwin's device number encoding.
15-18
: Implementation of Minor function is correct.The bit masking correctly extracts the minor number according to Darwin's device number encoding.
vendor/github.com/dgraph-io/ristretto/z/file_linux.go (2)
26-37
: Good implementation of Linux-specific Truncate method with clear error handlingThe implementation correctly follows the Linux-specific approach of synchronizing, truncating the file descriptor, and then using mremap to adjust the memory mapping size. Error handling is well-structured with descriptive error messages.
23-25
: Helpful comment explaining the platform-specific implementation differencesThe comment clearly documents the different approaches used for file truncation between Linux (truncate + mremap) and other systems (unmap + truncate + remap), which is valuable for maintenance.
vendor/golang.org/x/sys/unix/fdset.go (1)
26-30
: Implementation of Zero method looks goodThe method properly iterates through all elements of the Bits array and sets them to zero.
vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s (1)
14-30
: Assembly implementation follows standard pattern for syscall wrappersThe implementation correctly uses the NOSPLIT directive and redirects to the syscall package implementations. This is the standard approach for assembly wrappers around system calls.
vendor/github.com/dustin/go-humanize/.travis.yml (1)
18-21
: Good CI test practicesThe CI script includes important checks like gofmt, go vet, and testing with race detection, which are essential for maintaining code quality.
vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s (1)
1-30
: LGTM: Well-structured assembly implementation for RISC-V 64-bit BSD systemsThis assembly file correctly implements system call wrappers for the RISC-V 64-bit architecture on BSD systems. The implementation follows the standard pattern used in the Go standard library by jumping to the corresponding syscall package implementations.
The build constraints are properly set to limit compilation to the appropriate operating systems and when using the Go compiler. The NOSPLIT directives are correctly used to prevent stack splitting in these low-level functions.
vendor/github.com/dgryski/go-farm/farmhashmk.go (2)
8-18
: LGTM: Solid implementation of FarmHash helper functionThe
hash32Len5to12
function correctly implements the hashing algorithm for byte slices between 5 and 12 bytes in length, using the seed parameter and applying appropriate bit manipulation techniques.
87-102
: LGTM: Good implementation of Hash32WithSeedThe
Hash32WithSeed
function properly handles the seeded hashing case, delegating to the appropriate helper functions based on input length. The recursion for inputs longer than 24 bytes is correctly implemented.vendor/golang.org/x/sys/unix/asm_bsd_arm.s (1)
1-30
: LGTM: Well-structured assembly implementation for ARM BSD systemsThis assembly file correctly implements system call wrappers for the ARM architecture on BSD systems. The implementation follows the standard pattern by branching to the corresponding syscall package implementations.
The build constraints are properly set to limit compilation to FreeBSD, NetBSD, and OpenBSD when using the Go compiler. The NOSPLIT directives are correctly used to prevent stack splitting in these low-level functions.
vendor/github.com/dgraph-io/ristretto/z/mmap_wasip1.go (1)
1-41
: LGTM: Appropriate stub implementations for WASI platformThis file correctly provides stub implementations for memory mapping functions that aren't supported in the WebAssembly System Interface (WASI) environment. Returning
syscall.ENOSYS
is the appropriate way to indicate that these operations are not implemented on this platform.The approach allows for consistent API across platforms while gracefully handling the limitations of the WASI environment.
vendor/golang.org/x/sys/unix/fcntl_darwin.go (3)
9-12
: Implementation looks good.This function correctly wraps the
fcntl
syscall for integer arguments, providing a clean interface for Darwin-specific file control operations.
14-18
: Implementation correctly handles file locking operations.The function properly converts the
Flock_t
structure pointer usingunsafe.Pointer
for the syscall. This is a standard pattern when interfacing with system calls that require structure pointers.
20-24
: Implementation correctly handles preallocation operations.Similar to
FcntlFlock
, this function properly handles theF_PREALLOCATE
command with theFstore_t
structure, following the same pattern for syscall interfacing.vendor/golang.org/x/sys/unix/asm_bsd_386.s (2)
5-7
: Build constraints are properly configured.The build constraints correctly specify that this file should only be compiled for FreeBSD, NetBSD, or OpenBSD on 386 architecture when using the Go compiler.
16-29
: System call wrappers are correctly implemented.The assembly code properly defines syscall wrapper functions that jump to the corresponding implementations in the syscall package. This is the standard pattern for system call interfaces in Go.
vendor/golang.org/x/sys/unix/gccgo_c.c (3)
8-15
: Proper header inclusion and macro definition.The file correctly includes necessary headers and defines macros for assembly symbol naming to ensure proper integration with gccgo.
19-36
: Error handling in syscall wrapper is correctly implemented.The
gccgoRealSyscall
function properly initializeserrno
to zero before making the syscall and captures any error after the call. This ensures accurate error reporting when integrating with the Go runtime.
38-45
: Non-error returning syscall wrapper is correctly implemented.The
gccgoRealSyscallNoError
function provides a simpler interface when error reporting isn't needed. This is useful for syscalls where errors can be ignored or are handled elsewhere.vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go (2)
5-7
: Build constraints are properly configured.The build constraints correctly specify that this file should only be compiled for supported Unix-like operating systems.
15-47
: Alignment calculation is correctly implemented for cross-platform compatibility.The
cmsgAlignOf
function properly handles the various alignment requirements across different Unix-like operating systems and architectures. This is crucial for ensuring that socket control messages are properly formatted on all supported platforms.The implementation includes well-documented special cases for:
- AIX (no alignment)
- Darwin, iOS, Illumos, Solaris (32-bit alignment on 64-bit systems)
- NetBSD and OpenBSD arm (64-bit alignment)
- NetBSD arm64 (128-bit alignment)
- z/OS (integer-sized alignment)
vendor/golang.org/x/sys/unix/asm_bsd_arm64.s (1)
1-30
: Assembly implementation follows best practicesThe implementation correctly delegates system calls to the standard
syscall
package with proper build constraints for BSD systems on ARM64. The use ofNOSPLIT
is appropriate for these functions, and the stack frame sizes are correctly specified.vendor/github.com/dgraph-io/ristretto/z/mmap.go (1)
1-45
:✅ Verification successful
Well-designed memory mapping interface
The file provides a clean API for memory-mapped operations with good function documentation. Each function has a clear responsibility.
Note that this interface depends on platform-specific implementations of
mmap
,munmap
,madvise
, andmsync
functions that aren't visible in this file. Ensure those implementations provide appropriate error handling for system call failures across all supported platforms.
🏁 Script executed:
#!/bin/bash # Check for platform-specific implementations of the mmap functions find vendor/github.com/dgraph-io/ristretto/z/ -name "*mmap*" | grep -v "mmap.go"Length of output: 407
Clean and Well-Abstracted Memory Mapping Interface
The file provides a clear API for memory-mapped operations by delegating to platform-specific implementations. As verified, implementations exist in files for darwin, linux, plan9, unix, wasip1, and windows. Please ensure that each of these platform-specific functions properly handles error scenarios and any edge cases specific to their environment.
Overall, the abstraction aligns well with Go best practices and effectively isolates platform-dependent behaviors.
vendor/golang.org/x/sys/unix/asm_bsd_amd64.s (1)
1-30
: Assembly implementation follows best practicesThe implementation correctly delegates system calls to the standard
syscall
package with proper build constraints for BSD systems on AMD64. The use ofNOSPLIT
is appropriate for these functions, and the stack frame sizes are correctly specified.vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s (1)
1-32
: Well-structured assembly code for BSD system calls on ppc64This file correctly implements system call stubs for BSD systems on ppc64 architecture. The implementation follows standard Go assembly patterns by redirecting to the syscall package implementation.
vendor/github.com/dustin/go-humanize/ftoa.go (2)
8-24
: Function correctly removes trailing zeros from string representation of floatsThe implementation properly handles decimal points and efficiently removes trailing zeros from the string representation of a number.
26-38
: Function properly limits decimal places in float string representationThe implementation correctly handles different edge cases including:
- No decimal point in input
- Fewer decimal places than requested
- Negative or zero digit limits
vendor/golang.org/x/sys/unix/race.go (1)
5-7
: Build tags set correctly for race detectionThe build constraints correctly ensure this file is only compiled when race detection is enabled on the supported platforms.
vendor/github.com/google/uuid/sql.go (2)
15-52
: UUID Scan method correctly implements sql.Scanner interfaceThe implementation properly handles different input types:
- nil values (for NULL database values)
- Empty strings and byte slices
- String UUIDs that need parsing
- Raw 16-byte UUIDs
- Error handling for unsupported types
This will allow transparent reading of UUIDs from database results.
54-59
: UUID Value method correctly implements driver.Valuer interfaceThis method properly returns the string representation of the UUID, which is suitable for writing to most databases.
vendor/github.com/cespare/xxhash/v2/xxhash_other.go (3)
1-2
: Appropriate build constraints for non-optimized implementationsThe build tags correctly specify this implementation for non-amd64 architectures or specific environments (appengine, non-gc compiler, purego), serving as a fallback implementation when optimized versions aren't available.
5-62
: Well-implemented hash function with performance optimizationsThe
Sum64
function is correctly implemented with specific optimizations for different input sizes. The code appropriately uses different strategies for inputs ≥32 bytes versus smaller inputs, which aligns with xxHash algorithm design principles.The implementation matches the standard xxHash v2 algorithm, with proper handling of the initial seed values, multiple rounds of mixing, and the final avalanche step (lines 55-59).
64-76
: Efficient block processing implementationThe
writeBlocks
function correctly handles processing input data in 32-byte chunks, which is optimal for the xxHash algorithm. The function properly updates the digest state and returns the number of bytes processed.vendor/github.com/dustin/go-humanize/big.go (1)
7-19
:❓ Verification inconclusive
Consider potential overflow in order of magnitude calculation
The implementation of
oomm
function correctly calculates the order of magnitude with a maximum limit. However, there's a potential issue with the return value calculation that might lead to precision loss or incorrect results when handling very large integers.The expression
float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64()))
assumes thatn
,m
, andb
can be represented as int64 values. For large integers outside the range of int64, this might lead to precision issues.
🏁 Script executed:
#!/bin/bash # Check if this function is used with large integers in the codebase rg -A 2 -B 2 "oomm\("Length of output: 720
Attention: Review the precision of the
oomm
calculationThe current implementation converts
big.Int
values toint64
before converting them tofloat64
. This approach can lead to precision loss or overflow if any ofn
,m
, orb
contain values outside the 64-bit integer range.
- The return expression
float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64()))
assumes that the values inn
,m
, andb
will fit within anint64
.- Since the function is later used in
bigbytes.go
, verify whether input numbers may ever exceed the safeint64
range.- If there’s a possibility of larger values in your use case, consider switching to a conversion mechanism using
big.Float
or applying range checks to prevent potential inaccuracies.vendor/github.com/pkg/errors/Makefile (2)
5-6
: Comprehensive code quality check targetThe
check
target effectively aggregates multiple code quality verification steps, which is a good practice for ensuring code quality.
42-44
: Well-implemented gofmt checkThe gofmt check correctly verifies that the code is formatted according to Go standards and will fail if any files are not properly formatted.
vendor/golang.org/x/sys/unix/asm_linux_mipsx.s (4)
5-8
: Appropriate build constraints for MIPS architectureThe build tags correctly specify this assembly implementation for Linux on MIPS/MIPSLE architectures using the gc compiler.
19-27
: Efficient syscall implementation using jumpsThe syscall functions (
Syscall
,Syscall6
,Syscall9
,RawSyscall
,RawSyscall6
) are correctly implemented as jumps to the standard syscall package implementations, which is an efficient approach that ensures consistency with the runtime's handling of syscalls.Also applies to: 41-46
28-40
: Properly implemented SyscallNoError with runtime notificationsThe
SyscallNoError
function correctly notifies the Go runtime about syscall entry and exit usingruntime·entersyscall
andruntime·exitsyscall
, which is essential for proper goroutine scheduling during syscalls.The register setup for the MIPS architecture is correctly implemented, with:
- Arguments passed in registers R4, R5, R6
- Syscall number in R2
- Return values stored in R2, R3
47-55
: Correctly implemented RawSyscallNoErrorThe
RawSyscallNoError
function is properly implemented without runtime notifications, which is appropriate for syscalls that don't block or when the runtime doesn't need to be notified.The register usage follows the MIPS architecture syscall convention correctly.
vendor/golang.org/x/sys/unix/dev_freebsd.go (3)
1-13
: No issues with licensing and documentation.
All looks standard and aligned with the project's BSD-style header.
21-24
: Validate the mask for the minor component.
0xffff00ff
might exclude bits 8–15. Double-check that you intend to preserve or discard those bits.
16-19
:❓ Verification inconclusive
Confirm alignment with FreeBSD's major number encoding.
Shifting by 8 bits and masking with0xff
is often correct for FreeBSD, but ensure it matches the current FreeBSD definition.Run this script to confirm that the upstream FreeBSD constants align with the chosen shift and mask:
🏁 Script executed:
#!/bin/bash # Checking relevant definitions in FreeBSD headers: fd --type f --regex 'sys/types.h$' --exec cat {} \| rg 'st_rdev'Length of output: 67
Attention: Manual Verification Required for FreeBSD Major Number Encoding
The current implementation for extracting the major number using a shift of 8 bits and masking with
0xff
appears standard, but the automated script did not return the expected FreeBSD header definitions. Please manually verify the upstream FreeBSD documentation or system headers (e.g., in/usr/include/sys/types.h
or/usr/include/sys/mkdev.h
) to ensure this encoding fully aligns with FreeBSD’s major number definitions.
- Ensure that the current FreeBSD headers define major numbers using the same shift/mask combination.
- Confirm against official documentation or a reliable FreeBSD source if necessary.
vendor/golang.org/x/sys/unix/race0.go (7)
1-9
: Standard stub for race-disabled builds.
No issues found; these build tags and the package declaration look correct.
10-12
: Imports are minimal and appropriate.
No further changes necessary.
14-14
: raceenabled flag set to false.
This is appropriate for a stub implementation.
16-18
: No-op raceAcquire function.
Implementation is consistent with race-disabled environment.
19-21
: No-op raceReleaseMerge function.
Implementation is consistent with race-disabled environment.
22-24
: No-op raceReadRange function.
Implementation is consistent with race-disabled environment.
25-26
: No-op raceWriteRange function.
Implementation is consistent with race-disabled environment.vendor/golang.org/x/sys/unix/asm_linux_s390x.s (9)
1-4
: License and headers look correct.
No issues to address.
5-9
: Build tags for s390x on Linux with GC.
Matches standard Go patterns for architecture-specific assembly.
10-15
: Include directives for syscall bridging.
Implementation follows typical conventions.
19-21
: Syscall bridging.
Forwards directly tosyscall.Syscall
, which is expected for minimal overhead.
22-24
: Syscall6 bridging.
Matches standard patterns for multi-argument system calls.
25-38
: SyscallNoError routine.
Correctly invokes runtime calls to ensure consistent thread accounting.
40-42
: RawSyscall bridging.
No issues noted.
43-45
: RawSyscall6 bridging.
No issues noted.
46-57
: RawSyscallNoError functionality.
Properly implements no-error variant, preserving registers and returning results directly.vendor/github.com/dgryski/go-farm/fp_amd64.s (1)
1-1
: Auto-generated assembly file - no modifications needed.This file is auto-generated by a tool as indicated in the first line. It implements two fingerprint hash functions (
Fingerprint64
andFingerprint32
) optimized for the AMD64 architecture and appears to be correctly implemented.vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go (2)
28-35
: Unsafe operations used for performance optimization.The implementation leverages unsafe pointer operations to avoid unnecessary string-to-byte slice copying, which is a common performance optimization for hash functions. However, this approach relies on internal string and slice representations in Go, which could potentially change in future Go versions.
For long-term maintenance, consider adding tests that would detect if the implementation breaks due to changes in Go's internal representation of strings or slices.
39-46
: Similar unsafe pattern in WriteString method.This method mirrors the same unsafe approach used in Sum64String. Both implementations are common patterns for performance-critical code but should be monitored across Go version updates.
vendor/github.com/dgraph-io/ristretto/z/mmap_linux.go (2)
28-34
: Confirm file size casting to int.
Usingint(size)
in theunix.Mmap
call might introduce issues whensize
exceeds the maximum value forint
on 32-bit systems. Consider ensuring thatsize
will remain within safe limits for this cast or handle it gracefully if there's a risk of overflow.Would you like a script to locate all calls where
mmap
is invoked, to verify that larger file sizes aren’t passed in 32-bit environments?
36-55
: Check edge cases formunmap
.
The code checkslen(data) == 0 || len(data) != cap(data)
and returnsunix.EINVAL
. While this can prevent accidental misuse, ensure that there's no valid scenario in whichlen(data)
andcap(data)
might differ for a legitimate slice. Otherwise, this might lead to unintended errors for certain slices.vendor/golang.org/x/sys/unix/env_unix.go (1)
14-32
: Be mindful of concurrency risks with environment variables.
Environment variables are process-wide, so multiple goroutines changing or clearing them can lead to race conditions unless carefully respected. Either protect these calls with synchronization or accept that the environment is inherently global and non-thread-safe.vendor/golang.org/x/sys/unix/asm_linux_amd64.s (5)
17-19
: Confirm usage matchessyscall.Syscall
.
This direct jump defers to the standard library’s syscall package. Ensure that no unique or extended logic is needed before or after the jump.
20-22
: ValidateSyscall6
call sites.
Just likeSyscall
, this jump defers to the package’s logic. Confirm that any advanced usage (e.g., specifying arguments beyond three registers) matches the library’s expectations.
38-40
: ForwardingRawSyscall
Similar toSyscall
, but skipping certain runtime overhead. Ensure that the calling code handles any blocking or concurrency constraints appropriately.
41-43
:Syscall6
variant with no runtime overhead
CallingRawSyscall6
directly might skip scheduler synchronization. Double-check that the calling paths do not require safe points or preemption.
57-59
: Surfacegettimeofday
usage.
This jump references the standard library’sgettimeofday
. Confirm whether additional validation or time adjustments are needed in your application or if the raw values are sufficient.vendor/github.com/google/uuid/version7.go (2)
89-89
:✅ Verification successful
Confirm the existence of
timeMu
.
timeMu
is locked and unlocked withingetV7Time()
, but its declaration is not shown. Verify thattimeMu
is declared in the same package to ensure proper concurrency handling.
🏁 Script executed:
#!/bin/bash # Description: Search for the declaration of timeMu in the uuid package to confirm it's present. rg -A 3 "timeMu"Length of output: 1358
Confirmed
timeMu
existence and proper usage in the package.
The search shows thattimeMu
is declared invendor/github.com/google/uuid/time.go
as async.Mutex
, and it is correctly used (locked and unlocked) by functions in bothversion7.go
andtime.go
. There is no discrepancy in its declaration or usage that would affect concurrency handling.
23-30
:✅ Verification successful
Ensure correct usage of random source if the randomness pool is not explicitly enabled.
NewV7
usesNewRandom()
by default. Verify that all call-sites are aware of the source of randomness and thatEnableRandPool
or any custom pool usage is appropriately handled throughout the codebase.
🏁 Script executed:
#!/bin/bash # Description: Search for references to EnableRandPool or custom random usage to ensure consistent handling. rg -A 5 "EnableRandPool"Length of output: 2855
Verified Correct Usage of Random Source
We've confirmed that
NewV7
invendor/github.com/google/uuid/version7.go
correctly callsNewRandom()
, which internally respects the randomness pool if enabled viaEnableRandPool
. The related files (such asvendor/github.com/google/uuid/uuid.go
andvendor/github.com/google/uuid/version4.go
) consistently document and handle pool usage. No further changes are required at this call-site.vendor/github.com/dgraph-io/ristretto/z/calloc.go (2)
1-11
: Looks good!The atomic usage in
NumAllocBytes
is correct for concurrency, and no issues are apparent.
13-42
: StructMemStats
is well-documented.The structure and field-level documentation referencing JE Malloc is clear and follows best practices.
vendor/golang.org/x/sys/unix/mremap.go (2)
51-53
: No further issues found.This wrapper function cleanly delegates to
mapper.Mremap
.
26-49
:✅ Verification successful
Validate Go version compatibility for
unsafe.Slice
usage.Your usage of
unsafe.Slice
to construct the new slice is correct in modern Go. However, ensure the overall project enforces a suitable Go version (≥1.17) so thatunsafe.Slice
is consistently supported without undefined behavior.
🏁 Script executed:
#!/bin/bash # Description: Check for Go version constraints in go.mod and documented build instructions. rg -A 5 "go 1\."Length of output: 1395
Go Version Compatibility Confirmed for
unsafe.Slice
Usage
- Verified that the project's
go.mod
specifies Go version 1.24.0, which is well above the minimum requirement.- Confirmed from the vendor metadata that
golang.org/x/sys/unix
explicitly targets Go 1.17, ensuring thatunsafe.Slice
is fully supported.- The implementation in
vendor/golang.org/x/sys/unix/mremap.go
(lines 26–49) is therefore valid.vendor/github.com/google/uuid/marshal.go (4)
9-14
: MarshalText implementation looks good.The implementation properly encodes a UUID into a hexadecimal string representation as a byte slice, meeting the requirements of the
encoding.TextMarshaler
interface.
16-24
: UnmarshalText implementation looks correct.The implementation correctly parses a byte slice back into a UUID object, handling errors appropriately and satisfying the
encoding.TextUnmarshaler
interface.
26-29
: MarshalBinary implementation is efficient.The implementation simply returns the raw bytes of the UUID, which is an efficient approach for binary marshaling.
31-38
: UnmarshalBinary includes proper validation.The implementation correctly validates that the input data is exactly 16 bytes (the size of a UUID) before copying it, providing appropriate error handling.
vendor/golang.org/x/sys/unix/asm_linux_riscv64.s (5)
5-7
: Build tags are properly configured.The build tags correctly specify that this file is for RISC-V 64-bit architecture and the Go compiler (gc), ensuring the assembly code is only included in the appropriate builds.
17-22
: Syscall and Syscall6 implementations look correct.These functions properly jump to the corresponding syscall package implementations, maintaining consistency with the syscall package's behavior.
23-33
: SyscallNoError implementation follows RISC-V calling conventions.The implementation correctly:
- Notifies the Go runtime when entering/exiting the system call
- Places arguments in the appropriate registers (A0-A2)
- Places the syscall number in A7 as per RISC-V conventions
- Uses ECALL instruction to perform the system call
- Retrieves return values properly
This follows the standard RISC-V 64-bit syscall ABI.
35-40
: RawSyscall and RawSyscall6 implementations look correct.These functions properly jump to the corresponding syscall package implementations.
41-49
: RawSyscallNoError implementation follows RISC-V calling conventions.The implementation correctly places arguments in the appropriate registers and retrieves return values, but intentionally skips the runtime notifications, which is appropriate for a "raw" syscall.
vendor/golang.org/x/sys/unix/asm_linux_arm.s (6)
5-7
: Build tag is properly configured.The build tag correctly specifies that this file is for the Go compiler (gc), ensuring the assembly code is only included in the appropriate builds.
17-22
: Syscall and Syscall6 implementations look correct.These functions properly branch to the corresponding syscall package implementations with the B (branch) instruction.
23-37
: SyscallNoError implementation follows ARM calling conventions.The implementation correctly:
- Notifies the Go runtime when entering/exiting the system call with BL (branch with link)
- Places the syscall number in R7 as required by the ARM Linux ABI
- Places arguments in registers R0-R2
- Clears registers R3-R5 for unused arguments
- Uses SWI (Software Interrupt) to perform the system call
- Retrieves and handles return values properly
This follows the standard ARM syscall calling convention.
39-44
: RawSyscall and RawSyscall6 implementations look correct.These functions properly branch to the corresponding syscall package implementations.
45-54
: RawSyscallNoError implementation follows ARM calling conventions.The implementation correctly places the syscall number and arguments in the appropriate registers and retrieves return values, but intentionally skips the runtime notifications, which is appropriate for a "raw" syscall.
56-57
: seek implementation looks correct.This function properly branches to the syscall package's seek implementation.
vendor/github.com/cespare/xxhash/v2/README.md (4)
1-10
: README introduction is clear and informative.The introduction provides a good overview of the xxhash package, describing it as a Go implementation of the 64-bit xxHash algorithm with performance advantages over Go's standard library hashing functions.
11-26
: API documentation is well-structured.The API section clearly documents the main functions and types provided by the package, including the
Digest
type and its methods that implement thehash.Hash64
interface.
43-61
: Benchmark section provides useful performance data.The benchmark section effectively showcases the performance characteristics of both the pure-Go and assembly implementations across different input sizes, which is valuable information for potential users.
63-67
: Project references add credibility.Listing notable projects that use the package (InfluxDB, Prometheus, FreeCache) adds credibility and demonstrates the package's production-readiness.
vendor/golang.org/x/sys/unix/asm_linux_arm64.s (1)
1-54
: Bridging assembly appears standard and consistent with Go conventions.All generated functions simply delegate to the respective syscall implementations, with correct usage of runtime entersyscall/exitsyscall where needed. No issues observed.
vendor/golang.org/x/sys/unix/fcntl.go (1)
1-38
: Robust implementation of fcntl operations.The code follows standard patterns to manage file descriptors, commands, and arguments. Error handling is straightforward and returns appropriate syscalls' errno. Looks good overall.
vendor/golang.org/x/sys/unix/asm_linux_mips64x.s (1)
1-58
: Assembly stubs properly delegate syscalls to the Go runtime.This code closely mirrors other platform-specific syscall stubs. The entersyscall/exitsyscall logic is correctly used for the NoError variants. No issues found.
vendor/github.com/pkg/errors/go113.go (4)
1-2
: Build tag usage is appropriate.This file correctly specifies the Go version constraint (
go1.13
) for using the new error-wrapping functionalities.
9-16
: Re-exporting standard library’sIs
function appears correct.This wrapper around
stderrors.Is
correctly delegates the matching logic to the standard library. It is straightforward, offers no concurrency pitfalls, and follows Go 1.13+ error norms.
18-32
: Re-exporting standard library’sAs
function is aligned with best practices.This function follows the standard library’s semantics for error type assertions. The code is concise and correctly delegates behavior to
stderrors.As
.
33-38
: Unwrap function is properly delegated.The vendor code’s
Unwrap
simply callsstderrors.Unwrap
, maintaining consistency with the Go 1.13+ standard error wrapping approach. No further improvements needed.vendor/github.com/google/uuid/version4.go (5)
9-16
: Use ofMust(NewRandom())
is consistent with idiomatic UUID creation.This pattern of panicking upon UUID generation failure is standard for
Must
-type functions. Appears robust and straightforward.
17-24
: Straightforward approach to returning string form.
NewString
is a clean helper that clarifies usage for callers. Good approach to keep generation and conversion in one place.
25-44
: Pool usage logic is well-structured.When
poolEnabled
is true, the function efficiently delegates tonewRandomFromPool
. Otherwise, it generates a UUID directly. Error handling is properly returned to the caller, ensuring no silent failures.
46-56
: Error handling forio.ReadFull
is correct.
Nil, err
return ensures that any read failure surfaces rather than producing a partially formed UUID. The version bits are also correctly set to v4.
58-76
: Thread-safe UUID generation from random pool is properly synchronized.The
poolMu.Lock()
usage, error checks on replenishing the pool, and version bits application appear correctly handled. This approach avoids data races or half-initialized states.vendor/github.com/dgryski/go-farm/farmhashna.go (3)
26-51
: Length-based branching is logically sound.The helper function
hashLen0to16
correctly accounts for shorter slices by applying specialized sub-branches for small ranges (≥8, ≥4, >0) and returningk2
for empty slices. This helps optimize performance for small inputs.
155-161
: Seed-based variants offer extra flexibility.
naHash64WithSeed
andnaHash64WithSeeds
provide robust hashing variations, enabling custom seeds. No immediate enhancements or concurrency concerns here.
104-153
:✅ Verification successful
Loop-based hashing for >64 bytes is well-structured but verify large inputs.
The
naHash64
function processes data in 64-byte chunks, updating the internal state. The loop logic, including post-processing withhashLen16Mul()
, seems correct. Consider verifying performance on very large inputs, but as vendor code, it’s consistent with farmhash references.Run the following script to confirm no known performance regressions or major differences from official farmhash implementations:
🏁 Script executed:
#!/bin/bash # Compare lines of code or logic referencing farmhash in other vendor code rg "farmhash" -A 10Length of output: 1644
Loop-Based Hashing Implementation Looks Consistent with Official FarmHash
The implementation in
vendor/github.com/dgryski/go-farm/farmhashna.go
(lines 104–153) correctly processes inputs in 64-byte chunks and updates its internal state as expected. Verification via the README confirms that this is a mechanical translation of Google's FarmHash, so the logic—including the loop and post-processing usinghashLen16Mul()
—is consistent with the original reference.• The algorithm details align with the official FarmHash design.
• No discrepancies or performance regressions were apparent in the vendor-provided references.While the implementation appears correct, it is still advisable to run performance benchmarks on very large inputs to ensure parity with production benchmarks.
vendor/github.com/dgraph-io/ristretto/z/mmap_darwin.go (4)
27-35
: Ensure robust handling ofmmap
errors
This function correctly returns the error fromunix.Mmap
. For better observability, consider annotating the error with context or logs if needed.
37-40
:munmap
usage is straightforward
Unmapping memory viaunix.Munmap
is standard practice. Just ensure this function isn’t called on an already unmapped or truncated region to avoid runtime errors.
57-59
:msync
implementation looks correct
Synchronizing mapped memory viaunix.Msync
is the recommended approach.
42-55
:❓ Verification inconclusive
Confirm
madvise
support on Apple Silicon
Usingsyscall.Syscall
formadvise
is valid on Darwin due to missing support ingolang.org/x/sys/unix
. Verify it also behaves as expected on arm64.
🌐 Web query:
Is `syscall.SYS_MADVISE` fully supported on Darwin arm64 as of Go 1.20?
💡 Result:
The support for
syscall.SYS_MADVISE
on Darwin arm64 in Go 1.20 involves a mix of definitions and potential runtime issues, based on available documentation and historical context:
Syscall Definition:
TheSYS_MADVISE
syscall number (75
) is explicitly defined for Darwin arm64 in the Go syscall package, as seen in the code from the golang-codereviews group. This confirms its inclusion in the syscall table[5][9].Implementation Challenges:
However, historical issues highlight problems withmadvise()
on Darwin arm64. A 2016 bug report (issue #16850) documented crashes due tomadvise()
failures during memory scavenging, returning errors in contexts where other platforms succeeded[10]. While this predates Go 1.20, it underscores platform-specific instability risks.Syscall Handling in Go:
The generated syscall code for Darwin arm64 (zsyscall_darwin_arm64.go
) does not include direct wrappers formadvise
, suggesting it might rely on libSystem (/usr/lib/libSystem.B.dylib
) via CGO or indirect calls[3][12]. This contrasts with Linux, wheremadvise
is a direct syscall[2].Runtime Behavior:
The Go runtime on Darwin uses libSystem wrappers for syscalls, as seen in the assembly code for syscall trampolines[5][12]. This implies compatibility with Darwin’s stricter syscall policies (e.g., avoiding private APIs like___getdirentries64
[1]), but also potential divergence from Linux’s raw syscall behavior.Conclusion:
Whilesyscall.SYS_MADVISE
is defined for Darwin arm64 in Go 1.20, its operational reliability depends on the underlying libSystem implementation and runtime integration. Developers should testmadvise
-dependent code thoroughly on Apple Silicon devices, as historical edge cases (e.g., parameter validation, error handling) may persist. For memory management, prefer higher-level abstractions likesyscall.Mmap
unless low-level control is necessary.Citations:
- 1: syscall: darwin arm{,64} libSystem syscalls are not compliant with the App Store submissions golang/go#28984
- 2: https://man7.org/linux/man-pages/man2/madvise.2.html
- 3: https://go.dev/src/syscall/zsyscall_darwin_arm64.go
- 4: https://docs.rs/syscalls
- 5: https://groups.google.com/g/golang-codereviews/c/zDcWm8PI7_o/m/GOXwlw55IMwJ
- 6: https://www.dllhook.com/post/207.html
- 7: https://android.googlesource.com/platform/external/golang-x-sys/+/refs/heads/build-tools-release%5E1..refs/heads/build-tools-release/
- 8: https://lore.kernel.org/lkml/[email protected]/T/
- 9: https://blog.xhyeax.com/2022/04/28/arm64-syscall-table/
- 10: runtime: madvise() failure during scavenging causing crash on darwin arm64 golang/go#16850
- 11: https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md
- 12: https://gist.github.com/yamnikov-oleg/454f48c3c45b735631f2
- 13: https://go.dev/src/runtime/sys_darwin.go
- 14: affected/package: syscall golang/go#61528
Action Required: Confirm
madvise
Behavior on Apple SiliconThe code correctly uses
syscall.Syscall
withSYS_MADVISE
on Darwin. Our recent research confirms that whileSYS_MADVISE
is defined on Darwin arm64 in Go 1.20, historical issues (e.g., golang/go#16850) highlight potential runtime instability on Apple Silicon. Please ensure this functionality is thoroughly tested on arm64 devices, particularly focusing on parameter validation and error handling.
- Location:
vendor/github.com/dgraph-io/ristretto/z/mmap_darwin.go
(Lines 42-55)vendor/github.com/dgryski/go-farm/farmhashxo.go (5)
8-19
: Validate slice length forh32
Since this function reads from indices [0..15], confirm the caller ensureslen(s) >= 16
to avoid out-of-range panics.
21-32
: Double-check negative indexing forh32Seeds
Similar toh32
, this function accesses s[slen-16..slen], requiring at least 16 bytes. Verify upstream logic guarantees this size.
34-73
:xohashLen33to64
logic is cohesive
The multi-step hashing process appears consistent with the rest of the code. No immediate concerns.
75-84
:xohashLen65to96
function follows the same pattern
Usesh32
for the first 64 bytes and seeds the final 32 bytes. Implementation is logically aligned with neighboring functions.
86-104
: Confirm presence of helper functions inHash64
This function referenceshashLen0to16
,hashLen17to32
,naHash64
, anduoHash64
, which aren’t shown here. Ensure they exist and are tested.vendor/github.com/dustin/go-humanize/comma.go (4)
15-44
:Comma
function properly handles formatting
The logic for inserting commas inint64
values looks correct, including negative values and the special case formath.MinInt64
.
50-77
: Consider Infinity/NaN handling inCommaf
While typical floats are formatted properly, watch out for edge cases likemath.Inf
ormath.NaN
, which might yield unexpected output.
79-85
:CommafWithDigits
aligns well with rounding expectations
Limiting decimals by post-processing theCommaf
result is concise. Implementation appears correct.
89-116
:BigComma
handles large integer formatting properly
The approach for splitting giant numbers into 3-digit chunks is standard, and negative values are handled gracefully by storing and prepending the sign.vendor/golang.org/x/sys/unix/asm_linux_loong64.s (6)
1-8
: Build constraints are correctly definedThe build tags specify that this file should only be compiled for Linux on Loong64 architecture using the Go compiler, which is appropriate for this architecture-specific assembly code.
16-17
: Simple wrapper implementation looks goodThis is correctly implementing a jump to the syscall package's implementation of Syscall, which is a common pattern for syscall wrappers.
19-20
: Syscall6 wrapper is correctly implementedSimilar to the Syscall function, this correctly jumps to the syscall package's implementation.
22-35
: SyscallNoError implementation follows expected patternThe implementation correctly:
- Calls runtime.entersyscall
- Sets up registers (R4-R9) for the syscall parameters
- Performs the syscall
- Stores the result
- Calls runtime.exitsyscall before returning
This matches the pattern used for other architectures in the codebase.
37-41
: RawSyscall and RawSyscall6 wrappers look goodThese are correctly implemented as jumps to the syscall package's implementations.
43-54
: RawSyscallNoError implementation is correctThis implementation handles syscall parameters and results correctly for the Loong64 architecture. It properly sets up registers R4-R9, performs the syscall, and stores the result.
vendor/github.com/dgraph-io/ristretto/z/mmap_unix.go (6)
1-2
: Build constraints are correctly definedThe build tags ensure this file is only compiled on Unix-like systems while excluding specific platforms (Windows, Darwin, Plan9, Linux, WASI) where different implementations might be needed.
22-26
: Imports are appropriateThe file correctly imports the os package for file operations and the unix package from x/sys for the system calls needed for memory mapping.
28-36
: mmap implementation is correctThe function properly:
- Sets memory protection based on the writable flag
- Uses the appropriate unix.Mmap call with the correct parameters
- Returns the byte slice and any error from the syscall
This implementation follows standard patterns for memory-mapped files on Unix systems.
38-41
: munmap implementation is straightforwardThis correctly passes the byte slice to unix.Munmap for unmapping the memory.
43-52
: madvise implementation handles readahead flag correctlyThe function properly:
- Sets the advice flag based on the readahead parameter
- Uses MADV_NORMAL for readahead and MADV_RANDOM for random access
- Passes the correct parameters to unix.Madvise
This is a good practice for optimizing memory access patterns.
54-56
: msync implementation uses appropriate flagsThe function correctly uses the MS_SYNC flag to ensure synchronous writing of memory changes to the underlying file.
vendor/github.com/dustin/go-humanize/README.markdown (1)
1-125
: Well-structured documentation with clear examplesThe README provides comprehensive documentation for the go-humanize package, including:
- Purpose and installation instructions
- Detailed sections for each feature (sizes, times, ordinals, etc.)
- Clear examples with expected outputs
- References to external resources
This will be helpful for developers using the package.
vendor/github.com/dustin/go-humanize/si.go (7)
10-32
: Comprehensive SI prefix tableThe SI prefix table is complete and up-to-date, including all standard SI prefixes from quecto (10^-30) to quetta (10^30). This provides excellent coverage for a wide range of numerical values.
37-43
: Efficient reverse mapping with precomputed powersThe reverse mapping function not only creates the inverse map but also precomputes the power multipliers, which is an efficient optimization for later calculations.
47-55
: Clever regex construction for SI parsingThe init function dynamically builds a regex pattern using all SI prefixes from the table, which is an elegant approach that ensures the parser stays in sync with the defined prefixes.
64-85
: ComputeSI function handles edge cases properlyThe function correctly:
- Handles the special case of zero
- Calculates the appropriate exponent for SI prefixes
- Handles the special case of values that are exactly 1000.0
- Preserves the sign of the input value
This ensures accurate SI prefix computation across a wide range of inputs.
117-127
: ParseSI error handling is appropriateThe function properly checks for invalid input formats and returns clear errors. It also correctly handles parsing the float value and multiplying by the appropriate SI prefix magnitude.
95-108
:✅ Verification successful
String formatting functions reference undefined helpers
The SI and SIWithDigits functions call
Ftoa
andFtoaWithDigits
which aren't defined in this file. These are presumably defined elsewhere in the package.
🏁 Script executed:
#!/bin/bash # Check if Ftoa and FtoaWithDigits functions are defined in the package rg -r1 "func Ftoa" vendor/github.com/dustin/go-humanize/ rg -r1 "func FtoaWithDigits" vendor/github.com/dustin/go-humanize/Length of output: 368
Verification Complete: Helper Functions are Defined
After running the verification script, we confirmed that both
Ftoa
andFtoaWithDigits
are defined in the package (specifically invendor/github.com/dustin/go-humanize/ftoa.go
). Therefore, the concerns about undefined helpers in theSI
andSIWithDigits
functions are resolved.
57-64
:✅ Verification successful
Missing logn function reference
The ComputeSI function uses a
logn
function that isn't defined in this file. While it's likely defined elsewhere in the package, it would be helpful to verify this.
🏁 Script executed:
#!/bin/bash # Check if logn function is defined in the package rg -r1 "func logn" vendor/github.com/dustin/go-humanize/Length of output: 130
Logn function reference confirmed
The
logn
function is indeed defined within the package (located invendor/github.com/dustin/go-humanize/bytes.go
). The ComputeSI function correctly calls an existing utility from the package, so no code modifications are necessary. If clarity is a concern, consider enhancing the documentation by adding a comment noting the location of thelogn
implementation.vendor/github.com/dgryski/go-farm/farmhashcc.go (3)
42-51
: Confirm 128-to-64 downconversion approach.
hash128to64
uses a Murmur-inspired approach for folding a 128-bit hash into a 64-bit result. This is consistent with known hashing practices. Confirm you’ve validated collisions and distribution with representative data for your use cases.
98-169
: Ensure thorough testing across large inputs.
cityHash128WithSeed
handles rather complex logic, especially for large inputs ≥ 128 bytes. Verify boundary behaviors near 128, repeated blocks, and final tail handling. A robust test suite with random data of varying lengths is recommended.
171-177
: Suitability of default seeding.
cityHash128
usesk0, k1
as default seeds for short slices. That’s correct per the reference. If cryptographic collision resistance is desired (often not for hash-based lookups), consider more advanced seeds or a different library. Otherwise, this is fine for typical use cases.vendor/github.com/dgryski/go-farm/farmhashuo.go (1)
15-106
: Check for potential overflow in extended loops.
Hash64WithSeeds
performs repeated state updates in a loop, combining large sums and 64-bit multiples. Ensure no intermediate overflow occurs, especially if compiled for 32-bit systems. The final call touoH
also merges state. Broad test coverage across varying lengths is recommended.vendor/golang.org/x/sys/unix/asm_linux_386.s (3)
21-39
: Confirm consistent runtime transitions for SyscallNoError.Lines 27–39 use
runtime·entersyscall
andruntime·exitsyscall
. Confirm the rest of your 386 syscalls (Syscall, Syscall6) also handle transitions similarly. This helps the Go runtime manage goroutines pre-emptively.
47-57
: Alignment with typical system call patterns.
RawSyscallNoError
is consistent with typical usage ofAX
,BX
,CX
,DX
,SI
,DI
registers andint 0x80
. Just ensure you handle negative return values (for errors) in higher-level code if needed, as this version doesn’t handle error checking.
62-64
: Centralizing syscall definitions.
rawsocketcall
andseek
also simply jump to thesyscall
package. Consolidation is clean; no changes needed. Keep them if they must be distinct for linking or runtime introspection. Otherwise, consider referencing them in doc comments for clarity.Also applies to: 65-67
main.go (6)
6-6
: Imports look fine with newly introduced dependencies.
These imports (strconv, sync, ristretto, farm, structpb) seem appropriate for caching, hashing, and protobuf field handling. Ensure that yourgo.mod
file pins exact versions for reproducible builds, and keep an eye on any security advisories for these libraries.Also applies to: 8-8, 11-12, 16-16
64-64
: Client construction with cache reference is correct.
This line properly sets up the client with the newly created cache.
109-146
: Cache usage for GET commands with subscription is promising, but watch for non-string values.
- The logic to check and store string values is correct, but verify that the server consistently returns string responses for
"GET"
commands. Otherwise, type assertions might fail.- Consider how you might handle partial errors (e.g., if the server returns a different type in
resp.Value
).
204-204
: Properly waiting for all goroutines before closing.
Usingc.wg.Wait()
ensures no goroutine is left hanging afterClose()
. This is a clean approach for a graceful shutdown.
208-218
: Subscription logic is straightforward but always calls "GET.WATCH".
- If you plan to support multiple subscribe commands in the future, consider a more general approach or parameterizing the subscription command.
- Also watch for error handling strategies beyond just printing an error to the console (e.g., returning or retrying).
245-251
:Fingerprint
usage looks correct.
Generating a uint32 fingerprint usingfarm.Fingerprint32
is an efficient way to cache based on command strings. No concerns here.vendor/golang.org/x/sys/unix/dirent.go (3)
12-21
:readInt
functionality appears correct.
You correctly handle boundary checks and return(0, false)
if the slice is too short. This prevents out-of-bounds errors.
23-59
: Endian-specific reads are well structured.
readIntBE
andreadIntLE
properly handle 1, 2, 4, and 8-byte cases, and panic on unsupported sizes. This is a clear and maintainable approach.
61-103
:ParseDirent
logic is thorough.
- The loop discards invalid or empty entries and skips
"."
and".."
.- The boundary checks (e.g., for
reclen > len(buf)
) ensure safe parsing.
If there’s a use case for including.
or..
entries, consider parameterizing that behavior. Otherwise, this is effectively robust.vendor/golang.org/x/sys/unix/epoll_zos.go (5)
16-22
:EpollEvent
struct is consistent with a Linux-like layout.
The addedPad
field aligns with the Linuxepoll_event
struct size. If z/OS never transmits this struct to the kernel, you might removePad
once you confirm there's no need to mimic Linux alignment.
24-46
: Constants mirror typical epoll flags.
Marking unsupported flags for z/OS is a good practice to avoid confusion. The documentation clarifies the difference between Linux and z/OS features.
48-121
:epToPollEvt
andpToEpollEvt
conversions are succinct, but keep them updated.
You noted a TODO about possibly merging poll and epoll bit masks. That would simplify this mapping logic, but the current approach is still readable.
124-159
:epollcreate
,epollcreate1
, andepollctl
handle basic epoll operations.
- Error codes like
EBADF
andEEXIST
are well-placed.- Consider adding a check for invalid input (e.g., negative FDs), depending on how the rest of your code uses these APIs.
205-221
: High-level epoll functions are straightforward.
Your userland implementation ofEpollCreate
,EpollCreate1
,EpollCtl
, andEpollWait
provides a functional shim for z/OS.vendor/golang.org/x/sys/unix/asm_zos_s390x.s (1)
238-293
: Verify parameter offsets in 9-argument syscall.The assembly code for
syscall_syscall9
carefully writes each parameter into specific offsets like(2176+24)(R4)
,(2176+32)(R4)
, etc. If these offsets don't correctly match the expected LE structures or environmental control blocks, this could lead to corrupted parameters or undefined behavior.Please verify these offsets are correct for the z/OS s390x environment by examining the official IBM Language Environment documentation or any associated LE stack layout references.
vendor/golang.org/x/sys/unix/syscall.go (2)
37-44
: Sensible string conversion check.
ByteSliceFromString
properly checks for embedded NUL bytes and returnsEINVAL
if found, preventing partial truncation or corruption. This approach aligns with standard OS-level string handling.
69-85
: Risk of out-of-bound reads in BytePtrToString.Although documented, there is an inherent risk of a crash if the memory pointed to by
p
does not contain a terminating NUL. Make sure that any pointer passed in is guaranteed to be valid and NUL-terminated to avoid potential segmentation faults.Would you like a helper function or test to validate the pointer before usage?
vendor/github.com/dgraph-io/ristretto/z/rtutil.go (2)
51-54
: Hash not suitable for persistence.
MemHash
relies on the runtime’s hash seed, which changes per process. This is fine for in-memory hashing but unsafe for persistent storage. Ensure that keys hashed withMemHash
are never used as stable IDs across processes.
72-78
: Efficient memory clearing.
Memclr
employsmemclrNoHeapPointers
, which is efficient for zeroing slices without pointer overhead. This approach is safe for slices known to contain no pointers. Confirm that the target slices indeed do not store pointers to avoid memory safety issues.Would you like to add a check or comment clarifying that the slice does not contain pointer fields?
vendor/golang.org/x/sys/unix/fstatfs_zos.go (1)
61-80
: Validate thatFsid
consistently matches theDev
field.
When matchingstat.Fsid
tomnt_ent_buffer.filesys_info[i].Dev
, ensure the platform consistently treats both as unsigned 64-bit fields. Potential type mismatches or sign extensions could lead to hard-to-detect errors.vendor/golang.org/x/sys/unix/syscall_aix_ppc.go (2)
15-21
: Prevent potential overflow insetTimespec
andsetTimeval
.
sec
andnsec
(orusec
) can be large, and casting to 32-bit fields can lead to overflow on systems with timestamps beyond 2038. Verify if these fields must remain 32-bit for AIX PPC support.
23-37
: Validate numeric boundaries on length setters.
Usinguint32
orint32
might risk overflow or negative values if the caller inadvertently passes in out-of-spec lengths. Confirm that upstream code restricts the lengths to valid ranges to prevent potential out-of-bounds usage.vendor/golang.org/x/sys/unix/ioctl_unsigned.go (2)
19-21
: Check usage ofuintptr
for set operations.
uintptr(value)
inIoctlSetInt
fits many Unix ioctl definitions, but confirm the request codes never require a 64-bit pass or extended data structure.
27-30
: Confirm size alignment forIoctlSetPointerInt
.
int32(value)
aligns to the standard Cint
; still, ensure the underlying driver expects a 32-bit pointer value, not 64-bit.vendor/github.com/google/uuid/hash.go (3)
13-26
: No issues found with the namespace or special UUID definitions.The well-known namespaces and special forms (
Nil
andMax
) are introduced correctly, and the usage ofMust(Parse(...))
here appears consistent with typical patterns for namespace UUIDs.
45-51
: MD5-based UUID generation looks correct.No issues found. The function is a straightforward wrapper around
NewHash
with MD5.
53-59
: SHA1-based UUID generation looks correct.No issues found. The function is a straightforward wrapper around
NewHash
with SHA1.vendor/golang.org/x/sys/unix/pledge_openbsd.go (4)
24-59
: Well-structured implementation of the Pledge syscall.The version checks and error handling for
execpromises
on older OpenBSD releases are correct. Returning the raw error fromsyscall.Syscall
is consistent with typical patterns in Go’s syscall usage.
66-91
: Straightforward approach for changing only pledge promises.The function reuses the same version checks and omits
execpromises
, which aligns with its documented purpose.
98-123
: Straightforward approach for changing only pledge execpromises.Similar to
PledgePromises
, this function adjusts onlyexecpromises
while leavingpromises
untouched. The implementation is consistent with OpenBSD’s rules.
150-163
: Version-based pledge availability checks are correct.No major issues identified. The conditional checks for version compatibility and
execpromises
usage align with OpenBSD’s documented pledge requirements.vendor/golang.org/x/sys/unix/ioctl_zos.go (4)
20-22
: Generic integer-based ioctl usage is fine.No issues found. The function delegating to
ioctl
is straightforward.
34-43
: Termios set operation looks consistent.The check for valid
req
values and subsequent call toTcsetattr
is appropriate. Includingruntime.KeepAlive(value)
helps ensure the pointer remains valid during the system call.
50-54
: Integer retrieval from file descriptor.No issues found. This approach aligns with typical ioctl invocation patterns.
56-60
: Window size retrieval approach is acceptable.No issues found. The usage of a temporary
Winsize
struct and returning it as a pointer is standard.vendor/golang.org/x/sys/unix/sockcmsg_linux.go (4)
11-22
: Looks correct for credential passing.The approach of creating a buffer with
CmsgSpace(SizeofUcred)
, setting the levels and types, and writing theUcred
is standard for sending credentials via Unix domain sockets. No immediate issues found.
24-36
: Robust validation of expected socket control message level and type.Thanks for ensuring the code checks both
Level
andType
before decoding theUcred
. This helps avoid unintended parsing of unrelated control messages.
38-58
: Clean encoding of IPv4 and IPv6 packet info.Both
PktInfo4
andPktInfo6
correctly allocate and encode the data with properCmsgSpace
andCmsgLen
usage. This matches Linux kernel expectations for IP and IPv6 control messages.
60-85
: Comprehensive handling of original destination addresses.The switch on
(m.Header.Level, m.Header.Type)
is crucial for supporting both IPv4 and IPv6. ReturningEINVAL
by default is an appropriate fallback for unknown message types.vendor/github.com/pkg/errors/errors.go (3)
95-118
: Straightforward creation of new errors and formatted errors.Using
&fundamental{}
to capture stack traces at creation time is a reliable approach. The logic is clear, and no obvious issues are noted.
119-143
: Well-defined fundamental error structure.The code separates the message (
msg
) from the stack pointer, ensuring the stack trace is captured once. This design is consistent and clear.
264-289
: Thorough implementation ofCause
for retrieving root errors.The recursive approach terminates when the type no longer implements
causer
. This is a proven pattern for unwrapping complex error chains.vendor/golang.org/x/sys/unix/ioctl_signed.go (7)
14-21
: Safe integer setting with ioctl.Passing the integer directly as
uintptr(value)
is typical. Ensure that thereq
constants used here align with the correct ioctl on AIX or Solaris systems.
23-30
: Pointer-based integer ioctl usage.Using
unsafe.Pointer(&v)
with a localint32
ensures correct size for the data. Keep in mind potential endianness differences across platforms.
32-39
: Window size manipulation.The
Winsize
structure is platform-specific, and deferring thereq
parameter removal is logical for maintainability. Good job keeping the TODO visible.
41-47
: Termios struct usage.Similar to the Winsize comment, parameterizing the
req
is a flexible approach, though it may be streamlined in the future.
49-58
: Retrieving integer from ioctl.Appropriately returning
(value, err)
ensures the integer is captured even if an error occurs. This is consistent with typical ioctl usage.
60-64
: Get Winsize.Allocating a local
Winsize
and then returning a pointer is standard. No issues spotted.
66-70
: Get Termios.Mirrors the Winsize logic. Looks consistent and clear.
vendor/github.com/dgraph-io/ristretto/z/bbloom.go (2)
1-211
: Well-implemented Bloom filter data structureThis is a complete and efficient implementation of a Bloom filter, which is a space-efficient probabilistic data structure used to test whether an element is a member of a set. The implementation includes proper memory management, bit manipulation, and serialization/deserialization support.
153-157
: Efficient bit manipulation using unsafe pointersThe bit manipulation code using unsafe pointers is an efficient approach for Bloom filters where performance is critical. This is a common pattern in high-performance Go code when direct memory access is needed.
vendor/github.com/cespare/xxhash/v2/xxhash.go (3)
1-237
: Well-implemented xxHash algorithmThis is a thorough implementation of the 64-bit variant of xxHash (XXH64), a non-cryptographic hash function known for its high performance. The code properly implements the hash.Hash64 interface and includes optimizations.
19-31
: Detailed comments explaining implementation decisionsThe extensive comments explaining the reasoning behind using both constants and variables for prime numbers demonstrate good development practices. This helps other developers understand performance tradeoffs in the code.
167-199
: Proper binary marshaling implementationThe MarshalBinary and UnmarshalBinary implementations correctly handle serialization and deserialization of the hash state, including appropriate error checking and magic number validation.
vendor/github.com/dgraph-io/ristretto/z/z.go (2)
67-132
: Well-designed goroutine lifecycle managementThe
Closer
struct provides a robust pattern for managing goroutine lifecycles using a combination of context and WaitGroup. The implementation includes defensive nil checks and clear documentation.
134-150
: Efficient memory zeroing with fallbackThe
ZeroOut
function properly validates indices before zeroing memory. The commented-out alternative implementation serves as a clear fallback if theMemclr
function (which is likely more optimized) isn't available.vendor/golang.org/x/sys/unix/gccgo.go (3)
1-61
: Standard syscall implementation for gccgoThis file provides appropriate syscall wrappers specific to the gccgo compiler environment. The implementation follows the standard pattern of separating regular syscalls (which use Enter/Exitsyscall) from raw syscalls.
47-60
: Be cautious with Raw syscallsRaw syscalls bypass Go's scheduler since they don't call Enter/Exitsyscall. This makes them more efficient but potentially dangerous if they block, as they could prevent goroutine scheduling. Ensure these are only used when appropriate (typically for non-blocking calls).
5-6
: Clear build constraintsThe build constraints are well-defined, targeting gccgo compiler but excluding aix and hurd operating systems. Both the new-style
//go:build
and legacy-style// +build
tags are included for compatibility.vendor/github.com/dgraph-io/ristretto/z/btree.go (2)
31-35
: Validate pageSize alignment or negative fallback handling.
Whileos.Getpagesize()
typically returns a system-aligned page size, consider safeguarding for edge cases (e.g., unusual OS returns). You might guard against unexpected values, or at least log an error ifpageSize
is zero or negative.
352-357
: Careful with large-scale deletes.
DeleteBelow
compacts the tree for all keys whose value is below a given threshold. While functional, bulk deletions could fragment memory if performed repeatedly. Monitor performance and memory usage under large-scale or repeated compactions.vendor/golang.org/x/sys/unix/affinity_linux.go (1)
14-25
: Confirm_CPU_SETSIZE
coverage for large CPU counts.
cpuSetSize := _CPU_SETSIZE / _NCPUBITS
might not handle systems with more CPUs than_CPU_SETSIZE
. On such systems, you risk silently ignoring invalid CPU indexes. Confirm that_CPU_SETSIZE
is set to adequately cover your target CPU range or handle an error if it’s exceeded.vendor/golang.org/x/sys/unix/sockcmsg_unix.go (2)
16-26
: Robust alignment approach looks good.
TheCmsgLen
andCmsgSpace
functions correctly incorporate alignment for control message headers, ensuring consistency across various Unix-like platforms. This is a solid implementation.
77-90
: Implementation of UnixRights is aligned with best practices.
The approach to encode file descriptors into socket control messages is standard, and the usage ofSetLen
plus pointer arithmetic is consistent with cmsg best practices.vendor/github.com/dgraph-io/ristretto/z/file.go (2)
38-72
: Well-structured file initialization.
The logic inOpenMmapFileUsing
adequately handles empty files via truncation and gracefully returns a sentinel error to indicate file creation. Error wrapping provides good diagnostics.
91-106
: mmapReader implementation aligns with io.Reader.
The boundary checks are correct, incrementing offsets is clear, and returning partial copies followed by EOF is standard forio.Reader
.vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go (1)
45-47
: Time field shifting appears correct.
Shifting the nanosecond fields by 32 bits is a documented platform requirement on AIX ppc64. The fix preserves consistency for theTimespec
representation.vendor/github.com/dgraph-io/ristretto/z/histogram.go (6)
59-67
: Initialization logic looks good.
The constructor properly sets up bounds,CountPerBucket
, and initial min/max values. No immediate issues.
69-81
: Deep copy approach is correct.
The copy constructor duplicates slices properly, ensuring no shared backing array references.
112-118
: Edge case handling inMean()
.
Returning 0 whenCount == 0
is sensible to avoid NaN. This logic is fine.
120-167
: Improve clarity of bucketed output inString()
.
This code is solid. The usage ofstrings.Builder
is efficient, and bucket usage is well-labeled. No immediate errors found.
194-205
: Reset logic is straightforward.
Clear
properly resets the histogram’s critical fields. No immediate issues found.
27-35
:✅ Verification successful
Validate the presence of the
assert
function.
Lines 38 and elsewhere useassert(num > 4)
andassert(...)
, which is not a standard function in Go. Verify whether it's defined in this package or globally. If not present, these calls will fail during compilation.Run the following script to locate and confirm the definition of
assert
:
🏁 Script executed:
#!/bin/bash ast-grep --pattern $'func assert($_) { $$$ }'Length of output: 408
Assert function definition confirmed
I verified that the
assert
function is defined invendor/github.com/dgraph-io/ristretto/z/buffer.go
(lines 349–353). This confirms that its usage inhistogram.go
and elsewhere is valid and will compile as expected.vendor/github.com/google/uuid/uuid.go (8)
69-117
: Validate concurrency usage ofParse
.
All logic is read-only; concurrency should be fine if no shared state is mutated. Implementation looks robust with thorough format checks.
119-162
: Parses byte slices with consistent logic.
Mirrors the string-basedParse
function. Checks for standard and extended formats. Looks good.
174-240
: Validation and conversions appear consistent.
Methods likeFromBytes
,Must
, andValidate
handle length checks and format enforcement appropriately. No immediate concerns.
242-257
: String and URN generation appear standard.
Implementation aligns with the typicalxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
format. Straightforward.
259-283
: Hex encoding inencodeHex
is efficient.
No obvious correctness or performance issues.
285-311
: Version and variant retrieval is correct.
Logic to identify the variant, includingRFC4122
,Microsoft
, etc., is standard.Version()
extracts the top bits fromuuid[6]
.
313-350
: Document that enabling or disabling the rand pool is not thread-safe.
Callers must ensure no concurrent calls while toggling these states. This is mentioned in the doc, so the usage is okay.
355-365
:UUIDs.Strings()
method is a neat helper.
Implementation is straightforward, no issues found.vendor/github.com/dgraph-io/ristretto/z/allocator.go (7)
97-112
: Global overview ofAllocators
.
Allocators()
merges data from all allocated references for debugging. This is a useful diagnostic method. No immediate issues.
132-138
: AllocatorFrom usage.
RetrievingAllocator
byref
from the map is correct. Just confirm the lifecycle is well-managed (i.e.,Release()
is called).
140-158
: Ensure no infinite loop inSize()
.
The code calculates total used memory across buffers. Ifparse(pos)
references an unexpected buffer index,panic("Size should not reach here")
can occur. The logic seems correct as-is.
173-179
:Allocated
is a handy introspection.
It sums upcap(...)
for each buffer. This helps track usage. Implementation is straightforward.
196-214
:Release
cleans up references in the global map.
Implementation is correct; be sure to call it to avoid memory leaks.
313-365
:AllocatorPool
concurrency model.
A dedicated goroutine handles timed release, ensuring no usage conflict. The design appears correct if the caller respects the usage constraints (e.g., no concurrentfreeupAllocators()
calls).
68-91
:✅ Verification successful
Validate concurrency in
NewAllocator
.
This constructor modifies the global mapallocs
under a lock, which is correct. Just ensure that usage outside the constructor also consistently locks if needed.Could you confirm that
allocs
is only mutated here and inRelease()
?
🏁 Script executed:
#!/bin/bash ast-grep --pattern $'allocs[$_] = $_' ast-grep --pattern $'delete(allocs, $_)'Length of output: 233
Global allocations mutations verified under proper locking.
- Confirmed that the global map
allocs
is only mutated inNewAllocator
(line 88) and inRelease
(line 212) as shown by the AST pattern search.- Both locations use locking via
allocsMu
, ensuring consistent concurrency control.vendor/golang.org/x/sys/unix/syscall_aix.go (3)
23-37
: No immediate issues with these wrappers for AIX system calls.
They follow typical Go patterns for bridging toFaccessat
,Fchmodat
,Fchownat
, andOpen
. The direct calls appear correct for standard usage on AIX.
578-584
: Validate theUnmount
flags behavior.
The code returnsENOSYS
when flags are non-zero, implying AIX does not support unmounting with flags. This is correct for AIX, but consider clearly documenting it for developers expecting other Unix-like semantics.
359-373
:✅ Verification successful
Confirm the loop retry logic for
Wait4
onERESTART
.
The retry loop forWait4
is likely essential for AIX’s behavior, but please ensure no other edge cases require handling (e.g., potential infinite loop scenarios ifERESTART
is unexpectedly persistent).
🏁 Script executed:
#!/bin/bash # Searching for additional references to ERESTART usage across the codebase: rg -A 5 ERESTARTLength of output: 21370
Wait4 Retry Logic on ERESTART Confirmed
The retry loop in
Wait4
(invendor/golang.org/x/sys/unix/syscall_aix.go
lines 359–373) is intentionally set up for AIX’s behavior: it repeatedly callswait4
while the error equalsERESTART
. Our search shows that similar retry handling is consistently used across the codebase and aligns with the expectation that AIX may temporarily returnERESTART
when the process is still active. While the absence of a maximum retry safeguard means the loop could, in theory, run indefinitely ifwait4
persistently returnsERESTART
, this behavior is by design for AIX and is not an oversight. No additional edge cases requiring handling were identified.vendor/github.com/dgraph-io/ristretto/z/buffer.go (2)
172-235
: Ensure concurrency safety and robust error handling inGrow
.
The function automatically transitions fromUseCalloc
toUseMmap
by panicking on file errors. While this might be acceptable for a lower-level system, consider returning or propagating the error. Additionally, confirm that all usage contexts callGrow
from a single goroutine or protect with locks if necessary.
522-546
: Confirm post-Release
usage constraints.
OnceRelease
is called, the buffer’s memory is freed or unmapped. Document that the buffer must not be accessed afterward, as doing so would lead to undefined behavior.vendor/github.com/dgraph-io/ristretto/policy.go (3)
77-87
: Validate goroutine lifecycle innewDefaultPolicy
.
TheprocessItems()
goroutine runs untilp.stop
is closed. Ensure all references top
are done so under synchronization if multiple goroutines callAdd
,Push
, etc., concurrently.
216-221
: EnsureDel
concurrency safety.
Del
locks the entire policy viap.Lock()
, then callsevict.del(key)
. This appears correct, but confirm external usage always respects the same lock to avoid race conditions in higher-level code.
291-356
: Check concurrency forsampledLFU
updates.
p.used
andkeyCosts
are updated under thedefaultPolicy
lock, which is presumably correct. If you split logic under separate locks or anticipate usage outside the policy lock, you risk data races. Confirm the entire usage is properly synchronized.vendor/github.com/dgraph-io/ristretto/store.go (1)
153-182
: Verify thread safety ofm.em
updates.The
Set
method updates bothm.data
andm.em
. Ensure there's no race condition when multiple goroutines concurrently invokeSet
on the same shard and item key.vendor/golang.org/x/sys/unix/ioctl_linux.go (2)
9-18
: Implementation looks good.The
IoctlRetInt
function properly wraps the syscall and handles the error code. No immediate concerns with argument usage or error returns.
78-83
: Validate pointer usage inIoctlFileCloneRange
.Consider verifying that the
unsafe.Pointer(value)
is always valid and aligned. Although the current implementation is typical, extra checks can prevent undefined behavior on unusual architectures.vendor/golang.org/x/sys/unix/syscall_bsd.go (1)
24-35
: Confirm maximum path handling inGetwd
.
Getwd
uses a fixed buffer (PathMax
), which may be insufficient on certain systems with longer effective path lengths. Consider verifying that the buffer size covers all practical scenarios.vendor/github.com/dgraph-io/ristretto/cache.go (2)
161-213
:✅ Verification successful
Ensure
bucketDurationSecs
is defined and correct.The default assignment
config.TtlTickerDurationInSec = bucketDurationSecs
implies an external constant. Verify that this constant exists and has an appropriate default value for your TTL use cases. Also confirm that the half-value used forcleanupTicker
(line 183) meets your requirements.
🏁 Script executed:
#!/bin/bash # Description: Search for bucketDurationSecs definition and confirm it's set properly. rg -A 5 "bucketDurationSecs"Length of output: 1275
Verification complete:
bucketDurationSecs
is defined as expected.
- In
vendor/github.com/dgraph-io/ristretto/ttl.go
,bucketDurationSecs
is set toint64(5)
, which is then used incache.go
to initializeconfig.TtlTickerDurationInSec
when not provided.- The
cleanupTicker
is created using half of this value (i.e., 2.5 seconds), which appears to be the intended behavior based on performance considerations.
41-41
:✅ Verification successful
Confirm
storeItem
size from external declaration.
itemSize
usesunsafe.Sizeof(storeItem{})
, butstoreItem
is not defined in this file. Ensure that the externalstoreItem
definition remains stable soitemSize
accurately reflects the actual memory usage. IfstoreItem
changes size,itemSize
might become inconsistent.
🏁 Script executed:
#!/bin/bash # Description: Locate the definition of storeItem and check if it matches the usage in cache.go. fd storeItem.go --exec cat {} | rg "type storeItem"Length of output: 55
I'm not seeing any output from the initial search—this could mean that the definition of
storeItem
might reside in a different file or use a different naming pattern. To verify its definition more comprehensively, please run the following script:This will help locate where and how
storeItem
is defined so we can confirm that its size (used in cache.go) is accurate and stable. Once verified, we can ensure that any future changes tostoreItem
won't inadvertently break the memory size assumption incache.go
.
🏁 Script executed:
#!/bin/bash # Comprehensive search for the definition of storeItem in all Go files rg -n "type\s+storeItem\s+struct" .Length of output: 113
StoreItem Structure Consistency Verification
We confirmed that
storeItem
is defined externally in the filevendor/github.com/dgraph-io/ristretto/store.go
(line 25). SinceitemSize
incache.go
relies onunsafe.Sizeof(storeItem{})
, please ensure that any changes to thestoreItem
structure are carefully coordinated to maintain consistency in its computed memory footprint.
- File:
vendor/github.com/dgraph-io/ristretto/store.go
(line 25)- Concern: Future modifications to
storeItem
could inadvertently modify its size, impacting theitemSize
calculation incache.go
.vendor/github.com/dgraph-io/ristretto/z/simd/stub_search_amd64.go (2)
1-2
: Auto-generated code – no manual edits needed.These lines indicate that the code was automatically generated; manual modifications could be lost on regeneration.
5-6
:✅ Verification successful
Potential
int16
index overflow check.The function returns an
int16
index, which may overflow if the slice length exceeds 32767. Please confirm that slice sizes never approach this limit or consider using a larger integer type.You may run a search to ensure no call-sites pass slices that exceed the
int16
range:
🏁 Script executed:
#!/bin/bash # Searching for calls to Search and checking remarks on expected max lengths. rg "Search\(" -A 5Length of output: 6508
Slice Lengths Are Within Safe Bounds
After verifying the call sites (notably in
vendor/github.com/dgraph-io/ristretto/z/btree.go
and other SIMD search implementations), it appears that all slices passed toSearch
have controlled lengths that never approach the 32767 limit. The intended usage of the function and its call patterns ensure that an overflow is not a concern under current conditions. Please remain vigilant for any future changes that might allow larger slice sizes.vendor/github.com/dgraph-io/ristretto/z/simd/search_amd64.s (3)
1-2
: Auto-generated code – no manual edits needed.Likewise, these lines are from a generated assembly file; refrain from editing directly.
17-38
:✅ Verification successful
Loop unrolling logic verification.
The loop handles 4 elements per iteration while incrementing the index by 8. This is a known pattern, but confirm correctness if future changes alter the unrolled factor or slice usage constraints.
🏁 Script executed:
#!/bin/bash # Description: Searching for any references or disclaimers on 4-element unrolling. rg "unroll" -A 5Length of output: 598
Loop Unrolling Verification Complete
- The manual unrolling of four elements per iteration is consistent with similar patterns found in other vendor components (e.g., the unrolled inner loop in
vendor/github.com/dgryski/go-farm/farmhashcc.go
).- No removed or replaced code was missed; the current approach correctly increments the index by 8 per loop iteration.
- Please ensure that any future modifications to the unrolling factor or slice usage constraints are accompanied by a similar verification to maintain consistency.
54-59
:❓ Verification inconclusive
Ensure final index calculation is correct.
The bit-shift manipulations in the
NotFound
label can be tricky. Verify they consistently produce the desiredint16
index (including negative/not found scenarios).
🏁 Script executed:
#!/bin/bash # Checking for test coverage on the NotFound case or negative index scenario. rg "NotFound" -A 5Length of output: 20072
Double-check NotFound index arithmetic and add explicit test coverage
The assembly at
vendor/github.com/dgraph-io/ristretto/z/simd/search_amd64.s
(lines 54–59) calculates the final index using a branchless trick—essentially computing
(BX + (BX >> 31)) >> 1
.
While this technique appears to implement the logic of returningx>>1
for non-negative values and(x+1)>>1
for negatives (thereby yielding –1 when the original value indicates “not found”), the current codebase does not show any dedicated test cases for the negative or “not found” scenario.Action items:
- Verify Arithmetic:
Confirm that the arithmetic correctly handles all edge cases. In particular, double-check that when BX holds the “not found” sentinel value (or any negative index), the final value stored as anint16
is indeed what you intend (for example, –1).- Test Coverage:
If not already present, add unit tests that feed known edge-case inputs into the code path reaching theNotFound
label. This will ensure that the bit-shift sequence consistently produces the desired result.vendor/github.com/dgraph-io/ristretto/z/simd/search.go (3)
1-2
: Fallback build constraint comment.This file is excluded on amd64 builds, indicating a fallback search implementation for other architectures.
21-25
: Backup plan for short or non-multiple-of-8 slices.Falling back to
Naive(xs, k)
iflen(xs) < 8
orlen(xs) % 8 != 0
is a safe approach, ensuring no out-of-bounds reads occur.
31-50
:❓ Verification inconclusive
Validate large slice handling and index range.
Like in the assembly code, returning an
int16
could overflow if the slice can exceed 32767 elements. Confirm the maximum expected slice size.
🏁 Script executed:
#!/bin/bash # Searching for references to potential large array usage with the non-amd64 fallback. rg "Search\(" -A 8Length of output: 8834
Action: Verify that the slice sizes passed to this search function are always within bounds for an int16 result
The current implementation (vendor/github.com/dgraph-io/ristretto/z/simd/search.go, lines 31–50) mirrors the approach in both the baseline and assembly versions by returning an int16. However, as with the assembly code, this design assumes that the slice length (when divided by two) will never exceed 32767. Please confirm one of the following:
- The upstream or caller constraints ensure that the number of elements in xs is such that len(xs)/2 is always ≤ 32767.
- Or, consider introducing safeguards (or documenting the assumption) to prevent silent overflow if larger slices are ever passed.
func msync(b []byte) error { | ||
// TODO: Figure out how to do msync on Windows. | ||
return nil | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Implement msync functionality for Windows
The current implementation has a TODO comment and returns nil without actually synchronizing memory to disk. This could lead to data corruption or loss if the application relies on this function to ensure writes are persisted.
Consider implementing this functionality using FlushViewOfFile
and FlushFileBuffers
Windows API calls:
func msync(b []byte) error {
- // TODO: Figure out how to do msync on Windows.
- return nil
+ addr := uintptr(unsafe.Pointer(&b[0]))
+ if err := syscall.FlushViewOfFile(addr, uintptr(len(b))); err != nil {
+ return os.NewSyscallError("FlushViewOfFile", err)
+ }
+ return nil
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
func msync(b []byte) error { | |
// TODO: Figure out how to do msync on Windows. | |
return nil | |
} | |
func msync(b []byte) error { | |
addr := uintptr(unsafe.Pointer(&b[0])) | |
if err := syscall.FlushViewOfFile(addr, uintptr(len(b))); err != nil { | |
return os.NewSyscallError("FlushViewOfFile", err) | |
} | |
return nil | |
} |
func (uuid UUID) NodeID() []byte { | ||
var node [6]byte | ||
copy(node[:], uuid[10:]) | ||
return node[:] | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add version check before returning NodeID from UUID
The NodeID method doesn't verify that the UUID is version 1 or 2 before extracting the node ID, which could return meaningless data for other UUID versions.
func (uuid UUID) NodeID() []byte {
+ if uuid.Version() != 1 && uuid.Version() != 2 {
+ return nil
+ }
var node [6]byte
copy(node[:], uuid[10:])
return node[:]
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
func (uuid UUID) NodeID() []byte { | |
var node [6]byte | |
copy(node[:], uuid[10:]) | |
return node[:] | |
} | |
func (uuid UUID) NodeID() []byte { | |
if uuid.Version() != 1 && uuid.Version() != 2 { | |
return nil | |
} | |
var node [6]byte | |
copy(node[:], uuid[10:]) | |
return node[:] | |
} |
branches: | ||
except: | ||
- release | ||
|
||
branches: | ||
only: | ||
- master | ||
- develop | ||
- travis |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove duplication of the branches
key.
YAML does not allow defining the same key multiple times in the same hierarchy. Unify both “only” and “except” into a single branches
block to avoid parsing errors:
-branches:
- except:
- - release
-
-branches:
- only:
- - master
- - develop
- - travis
+branches:
+ only:
+ - master
+ - develop
+ - travis
+ except:
+ - release
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
branches: | |
except: | |
- release | |
branches: | |
only: | |
- master | |
- develop | |
- travis | |
branches: | |
only: | |
- master | |
- develop | |
- travis | |
except: | |
- release |
🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 9-9: duplication of key "branches" in mapping
(key-duplicates)
func fetchStat(s string) uint64 { | ||
var out uint64 | ||
sz := unsafe.Sizeof(&out) | ||
C.je_mallctl( | ||
(C.CString)(s), // Query: eg: stats.allocated, stats.resident, etc. | ||
unsafe.Pointer(&out), // Variable to store the output. | ||
(*C.size_t)(unsafe.Pointer(&sz)), // Size of the output variable. | ||
nil, // Input variable used to set a value. | ||
0) // Size of the input variable. | ||
return out | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prevent memory leaks and handle mallctl return codes.
In fetchStat
, each call to C.CString(s)
allocates memory that is never freed. Additionally, the return value of C.je_mallctl
is ignored, resulting in silent failures if an error occurs. Free the allocated string and consider handling je_mallctl
's return code. For instance:
func fetchStat(s string) uint64 {
- var out uint64
- sz := unsafe.Sizeof(&out)
- C.je_mallctl(
- (C.CString)(s),
- unsafe.Pointer(&out),
- (*C.size_t)(unsafe.Pointer(&sz)),
- nil,
- 0)
- return out
+ cs := C.CString(s)
+ defer C.free(unsafe.Pointer(cs))
+
+ var out uint64
+ sz := unsafe.Sizeof(&out)
+ ret := C.je_mallctl(
+ cs,
+ unsafe.Pointer(&out),
+ (*C.size_t)(unsafe.Pointer(&sz)),
+ nil,
+ 0)
+ // Optionally check ret != 0 and handle or log errors.
+ return out
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
func fetchStat(s string) uint64 { | |
var out uint64 | |
sz := unsafe.Sizeof(&out) | |
C.je_mallctl( | |
(C.CString)(s), // Query: eg: stats.allocated, stats.resident, etc. | |
unsafe.Pointer(&out), // Variable to store the output. | |
(*C.size_t)(unsafe.Pointer(&sz)), // Size of the output variable. | |
nil, // Input variable used to set a value. | |
0) // Size of the input variable. | |
return out | |
} | |
func fetchStat(s string) uint64 { | |
cs := C.CString(s) | |
defer C.free(unsafe.Pointer(cs)) | |
var out uint64 | |
sz := unsafe.Sizeof(&out) | |
ret := C.je_mallctl( | |
cs, // Query: eg: stats.allocated, stats.resident, etc. | |
unsafe.Pointer(&out), // Variable to store the output. | |
(*C.size_t)(unsafe.Pointer(&sz)), // Size of the output variable. | |
nil, // Input variable used to set a value. | |
0) // Size of the input variable. | |
// Optionally check ret != 0 and handle or log errors. | |
return out | |
} |
func (sf *SuperFlag) GetBool(opt string) bool { | ||
val := sf.GetString(opt) | ||
if val == "" { | ||
return false | ||
} | ||
b, err := strconv.ParseBool(val) | ||
if err != nil { | ||
err = errors.Wrapf(err, | ||
"Unable to parse %s as bool for key: %s. Options: %s\n", | ||
val, opt, sf) | ||
log.Fatalf("%+v", err) | ||
} | ||
return b | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Prefer returning errors instead of using log.Fatalf.
For GetBool
, on parse failure it calls log.Fatalf
. This forces termination. In a library context, returning the error might be more user-friendly. Unless this package is strictly for internal usage, consider a more recoverable approach.
func (a *Allocator) Allocate(sz int) []byte { | ||
if a == nil { | ||
return make([]byte, sz) | ||
} | ||
if sz > maxAlloc { | ||
panic(fmt.Sprintf("Unable to allocate more than %d\n", maxAlloc)) | ||
} | ||
if sz == 0 { | ||
return nil | ||
} | ||
for { | ||
pos := atomic.AddUint64(&a.compIdx, uint64(sz)) | ||
bufIdx, posIdx := parse(pos) | ||
buf := a.buffers[bufIdx] | ||
if posIdx > len(buf) { | ||
a.Lock() | ||
newPos := atomic.LoadUint64(&a.compIdx) | ||
newBufIdx, _ := parse(newPos) | ||
if newBufIdx != bufIdx { | ||
a.Unlock() | ||
continue | ||
} | ||
a.addBufferAt(bufIdx+1, sz) | ||
atomic.StoreUint64(&a.compIdx, uint64((bufIdx+1)<<32)) | ||
a.Unlock() | ||
// We added a new buffer. Let's acquire slice the right way by going back to the top. | ||
continue | ||
} | ||
data := buf[posIdx-sz : posIdx] | ||
return data | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Core Allocate
logic and concurrency.
While it uses atomic operations for index updates, it only acquires a Lock()
if the current buffer space is insufficient. Consider verifying that no data race occurs on the slice reference itself.
b.Grow(n) | ||
assert(n == copy(b.buf[b.offset:], p)) | ||
b.offset += uint64(n) | ||
return n, nil | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Safely handle write errors.
If the underlying buffer is out of memory or if an IO issue arises in the future (e.g., mmap
truncation), writing could fail. Consider supporting error returns to gracefully handle such cases without panicking.
isClosed bool | ||
// cost calculates cost from a value. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prevent data races on isClosed
.
Accessing isClosed
across multiple goroutines can cause data races. Reads (e.g., in Get
or Wait
) and writes (e.g., in Close
) happen without any synchronization. Converting it to an atomic or protecting it with a lock can fix this.
- isClosed bool
+ isClosed uint32 // store as atomic flag
...
- if c.isClosed {
+ if atomic.LoadUint32(&c.isClosed) == 1 {
...
- c.isClosed = true
+ atomic.StoreUint32(&c.isClosed, 1)
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
isClosed bool | |
// cost calculates cost from a value. | |
isClosed uint32 // store as atomic flag | |
// cost calculates cost from a value. |
func Clever(xs []uint64, k uint64) int16 { | ||
if len(xs) < 8 { | ||
return Naive(xs, k) | ||
} | ||
var twos, pk [4]uint64 | ||
pk[0] = k | ||
pk[1] = k | ||
pk[2] = k | ||
pk[3] = k | ||
for i := 0; i < len(xs); i += 8 { | ||
twos[0] = xs[i] | ||
twos[1] = xs[i+2] | ||
twos[2] = xs[i+4] | ||
twos[3] = xs[i+6] | ||
if twos[0] >= pk[0] { | ||
return int16(i / 2) | ||
} | ||
if twos[1] >= pk[1] { | ||
return int16((i + 2) / 2) | ||
} | ||
if twos[2] >= pk[2] { | ||
return int16((i + 4) / 2) | ||
} | ||
if twos[3] >= pk[3] { | ||
return int16((i + 6) / 2) | ||
} | ||
|
||
} | ||
return int16(len(xs) / 2) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Potential out-of-bounds accesses in Clever function.
The Clever
function accesses elements like xs[i+2]
, xs[i+4]
, and xs[i+6]
without ensuring these indices are within bounds. This could lead to panics if the slice doesn't have enough elements.
Also, the function replicates the key into a 4-element array but then performs individual comparisons, which seems unnecessary.
func Clever(xs []uint64, k uint64) int16 {
if len(xs) < 8 {
return Naive(xs, k)
}
var twos, pk [4]uint64
pk[0] = k
pk[1] = k
pk[2] = k
pk[3] = k
- for i := 0; i < len(xs); i += 8 {
+ for i := 0; i < len(xs)-7; i += 8 {
twos[0] = xs[i]
twos[1] = xs[i+2]
twos[2] = xs[i+4]
twos[3] = xs[i+6]
if twos[0] >= pk[0] {
return int16(i / 2)
}
if twos[1] >= pk[1] {
return int16((i + 2) / 2)
}
if twos[2] >= pk[2] {
return int16((i + 4) / 2)
}
if twos[3] >= pk[3] {
return int16((i + 6) / 2)
}
}
return int16(len(xs) / 2)
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
func Clever(xs []uint64, k uint64) int16 { | |
if len(xs) < 8 { | |
return Naive(xs, k) | |
} | |
var twos, pk [4]uint64 | |
pk[0] = k | |
pk[1] = k | |
pk[2] = k | |
pk[3] = k | |
for i := 0; i < len(xs); i += 8 { | |
twos[0] = xs[i] | |
twos[1] = xs[i+2] | |
twos[2] = xs[i+4] | |
twos[3] = xs[i+6] | |
if twos[0] >= pk[0] { | |
return int16(i / 2) | |
} | |
if twos[1] >= pk[1] { | |
return int16((i + 2) / 2) | |
} | |
if twos[2] >= pk[2] { | |
return int16((i + 4) / 2) | |
} | |
if twos[3] >= pk[3] { | |
return int16((i + 6) / 2) | |
} | |
} | |
return int16(len(xs) / 2) | |
} | |
func Clever(xs []uint64, k uint64) int16 { | |
if len(xs) < 8 { | |
return Naive(xs, k) | |
} | |
var twos, pk [4]uint64 | |
pk[0] = k | |
pk[1] = k | |
pk[2] = k | |
pk[3] = k | |
for i := 0; i < len(xs)-7; i += 8 { | |
twos[0] = xs[i] | |
twos[1] = xs[i+2] | |
twos[2] = xs[i+4] | |
twos[3] = xs[i+6] | |
if twos[0] >= pk[0] { | |
return int16(i / 2) | |
} | |
if twos[1] >= pk[1] { | |
return int16((i + 2) / 2) | |
} | |
if twos[2] >= pk[2] { | |
return int16((i + 4) / 2) | |
} | |
if twos[3] >= pk[3] { | |
return int16((i + 6) / 2) | |
} | |
} | |
return int16(len(xs) / 2) | |
} |
func Parallel(xs []uint64, k uint64) int16 { | ||
cpus := runtime.NumCPU() | ||
if cpus%2 != 0 { | ||
panic(fmt.Sprintf("odd number of CPUs %v", cpus)) | ||
} | ||
sz := len(xs)/cpus + 1 | ||
var wg sync.WaitGroup | ||
retChan := make(chan int16, cpus) | ||
for i := 0; i < len(xs); i += sz { | ||
end := i + sz | ||
if end >= len(xs) { | ||
end = len(xs) | ||
} | ||
chunk := xs[i:end] | ||
wg.Add(1) | ||
go func(hd int16, xs []uint64, k uint64, wg *sync.WaitGroup, ch chan int16) { | ||
for i := 0; i < len(xs); i += 2 { | ||
if xs[i] >= k { | ||
ch <- (int16(i) + hd) / 2 | ||
break | ||
} | ||
} | ||
wg.Done() | ||
}(int16(i), chunk, k, &wg, retChan) | ||
} | ||
wg.Wait() | ||
close(retChan) | ||
var min int16 = (1 << 15) - 1 | ||
for i := range retChan { | ||
if i < min { | ||
min = i | ||
} | ||
} | ||
if min == (1<<15)-1 { | ||
return int16(len(xs) / 2) | ||
} | ||
return min | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve error handling and performance in Parallel function.
The function panics if the number of CPUs is odd, which is not a graceful error handling approach. It should adapt to any number of CPUs.
Also, the constant (1 << 15) - 1
is used as a sentinel value without explanation. Consider defining it as a named constant for better readability.
func Parallel(xs []uint64, k uint64) int16 {
cpus := runtime.NumCPU()
- if cpus%2 != 0 {
- panic(fmt.Sprintf("odd number of CPUs %v", cpus))
- }
+ // Ensure even number of CPUs for consistency
+ if cpus%2 != 0 {
+ cpus--
+ }
sz := len(xs)/cpus + 1
var wg sync.WaitGroup
retChan := make(chan int16, cpus)
for i := 0; i < len(xs); i += sz {
end := i + sz
if end >= len(xs) {
end = len(xs)
}
chunk := xs[i:end]
wg.Add(1)
go func(hd int16, xs []uint64, k uint64, wg *sync.WaitGroup, ch chan int16) {
for i := 0; i < len(xs); i += 2 {
if xs[i] >= k {
ch <- (int16(i) + hd) / 2
break
}
}
wg.Done()
}(int16(i), chunk, k, &wg, retChan)
}
wg.Wait()
close(retChan)
+ const maxInt16 = (1 << 15) - 1 // Define sentinel value as a named constant
- var min int16 = (1 << 15) - 1
+ var min int16 = maxInt16
for i := range retChan {
if i < min {
min = i
}
}
- if min == (1<<15)-1 {
+ if min == maxInt16 {
return int16(len(xs) / 2)
}
return min
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
func Parallel(xs []uint64, k uint64) int16 { | |
cpus := runtime.NumCPU() | |
if cpus%2 != 0 { | |
panic(fmt.Sprintf("odd number of CPUs %v", cpus)) | |
} | |
sz := len(xs)/cpus + 1 | |
var wg sync.WaitGroup | |
retChan := make(chan int16, cpus) | |
for i := 0; i < len(xs); i += sz { | |
end := i + sz | |
if end >= len(xs) { | |
end = len(xs) | |
} | |
chunk := xs[i:end] | |
wg.Add(1) | |
go func(hd int16, xs []uint64, k uint64, wg *sync.WaitGroup, ch chan int16) { | |
for i := 0; i < len(xs); i += 2 { | |
if xs[i] >= k { | |
ch <- (int16(i) + hd) / 2 | |
break | |
} | |
} | |
wg.Done() | |
}(int16(i), chunk, k, &wg, retChan) | |
} | |
wg.Wait() | |
close(retChan) | |
var min int16 = (1 << 15) - 1 | |
for i := range retChan { | |
if i < min { | |
min = i | |
} | |
} | |
if min == (1<<15)-1 { | |
return int16(len(xs) / 2) | |
} | |
return min | |
} | |
func Parallel(xs []uint64, k uint64) int16 { | |
cpus := runtime.NumCPU() | |
// Ensure even number of CPUs for consistency | |
if cpus%2 != 0 { | |
cpus-- | |
} | |
sz := len(xs)/cpus + 1 | |
var wg sync.WaitGroup | |
retChan := make(chan int16, cpus) | |
for i := 0; i < len(xs); i += sz { | |
end := i + sz | |
if end >= len(xs) { | |
end = len(xs) | |
} | |
chunk := xs[i:end] | |
wg.Add(1) | |
go func(hd int16, xs []uint64, k uint64, wg *sync.WaitGroup, ch chan int16) { | |
for i := 0; i < len(xs); i += 2 { | |
if xs[i] >= k { | |
ch <- (int16(i) + hd) / 2 | |
break | |
} | |
} | |
wg.Done() | |
}(int16(i), chunk, k, &wg, retChan) | |
} | |
wg.Wait() | |
close(retChan) | |
const maxInt16 = (1 << 15) - 1 // Define sentinel value as a named constant | |
var min int16 = maxInt16 | |
for i := range retChan { | |
if i < min { | |
min = i | |
} | |
} | |
if min == maxInt16 { | |
return int16(len(xs) / 2) | |
} | |
return min | |
} |
@ayushsatyam146 Let's take them as dependency and not clone the repo. do not have a vendor folder. |
9489d36
to
a2f805f
Compare
Summary by CodeRabbit
I'll help you craft concise release notes for the pull request. Based on the comprehensive summary, here are the key release notes:
Release Notes
Dependency Updates
github.com/dgraph-io/ristretto
for cachinggithub.com/dgryski/go-farm
for hashing functionsgithub.com/dustin/go-humanize
for human-readable formattinggithub.com/google/uuid
to latest versiongithub.com/pkg/errors
for enhanced error handlingCaching Improvements
Hashing and Fingerprinting
System Compatibility